Jump to content

clarification...


dennismonsewicz

Recommended Posts

By default you can use variables in double brackets.

 

<pre><?php

$test = 'World';

echo "Hello $test \n";

# Won't work!
echo 'Hello $test \n';

echo "\n";

$arr = array( 'str' => 'World' );

# echo "Hello $arr['world']" is a little complex with the mixed quotes... as
# echo "Hello $arr["world"]" is acceptable as well... to avoid making exceptions,
# you use
echo "Hello {$arr["str"]} \n";

$arr2 = array( 'World' );

# You don't have to with numeric keys
echo "Hello $arr2[0] \n";

?></pre>

Link to comment
Share on other sites

The first syntax results in fewer syntax errors (at least in posts seen in these forums) because there are less different elements involved.

 

The first syntax places the variable inside of the double-quoted string and forces php to recognize where the variable starts and ends and it allows the single-quotes around the index string name to be used as is. I don't recall any people that use this simpler looking syntax needing help with syntax errors.

 

The second syntax places the variable outside of the double-quoted string by closing the double-quote, concatenate the variable with it, then concatenates another double-quoted string after the variable. For a single variable it is usually not a problem, but for multiple variables, this syntax is hard to read and apparently hard to type based on the number of people posting in forums that have syntax errors and cannot see what is wrong.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.