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
https://forums.phpfreaks.com/topic/126329-clarification/#findComment-653241
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
https://forums.phpfreaks.com/topic/126329-clarification/#findComment-653245
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.