Saturday, September 29, 2018

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.

Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...