I dimly recall, from my first readings of the PHP docs (more than 10 years ago) that the array-like syntax to access characters in arrays ($string[0]
) posed some ambiguity or undefined behaviour.
The O'Reilly PHP Pocket Reference (2nd ed) states:
To solve an ambiguity problem between strings and arrays, a new syntax has been introduced to dereference individual characters from strings:
$string{2}
This syntax is equivalent to
$string[2]
, and is preferable.
I understand that $string[2]
might be confusing, but I'm not sure how it could be ambiguous?
Furthermore: I wonder how the new syntax $string{2}
removes the ambiguity/confusion, considering that the curly braces (apparently) also work for "real" arrays.
The only ambiguity is that if you're expecting an array, but actually have a string, $var[0]
will give you the first byte of the string instead of the first array element. This may lead to a lot of head scratching and wondering why PHP is only giving you the first character instead of the whole array element. This is even more true for non-numeric indexes like $var['foo']
, which actually works if $var
is a string (yeah, please don't ask). I.e. it may make debugging slightly more difficult if your program is wrong in the first place.
There's no ambiguity for correct programs, since a variable cannot be a string and an array at the same time.
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