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?
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.
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.
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.
=> 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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With