Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpolation (double quoted string) of Associative Arrays in PHP

When interpolating PHP's string-indexed array elements (5.3.3, Win32) the following behavior may be expected or not:

$ha = array('key1' => 'Hello to me');  print $ha['key1'];   # correct (usual way) print $ha[key1];     # Warning, works (use of undefined constant)  print "He said {$ha['key1']}"; # correct (usual way) print "He said {$ha[key1]}";   # Warning, works (use of undefined constant)  print "He said $ha['key1']";   # Error, unexpected T_ENCAPSED_AND_WHITESPACE print "He said $ha[ key1 ]";   # Error, unexpected T_ENCAPSED_AND_WHITESPACE print "He said $ha[key1]";     # !! correct (How Comes?) 

Inerestingly, the last line seems to be correct PHP code. Any explanations? Can this feature be trusted?


Edit: The point of the posting now set in bold face in order to reduce misunderstandings.
like image 411
rubber boots Avatar asked Jan 19 '11 17:01

rubber boots


People also ask

Does PHP have string interpolation?

PHP String formatting String interpolationYou can also use interpolation to interpolate (insert) a variable within a string. Interpolation works in double quoted strings and the heredoc syntax only.

Do keep associative array inside double quote while printing otherwise it would not return any value?

Associative Arrays Instead, we could use the employees names as the keys in our associative array, and the value would be their respective salary. NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

Which one is correct syntax of associative array in PHP?

Associative array will have their index as string so that you can establish a strong association between key and values. The associative arrays have names keys that is assigned to them. $arr = array( "p"=>"150", "q"=>"100", "r"=>"120", "s"=>"110", "t"=>"115"); Above, we can see key and value pairs in the array.

What does => mean in PHP array?

=> is the separator for associative arrays. In the context of that foreach loop, it assigns the key of the array to $user and the value to $pass .


1 Answers

Yes, you may trust it. All ways of interpolation a variable are covered in the documentation pretty well.

If you want to have a reason why this was done so, well, I can't help you there. But as always: PHP is old and has evolved a lot, thus introducing inconsistent syntax.

like image 111
NikiC Avatar answered Sep 19 '22 11:09

NikiC