String - array ambiguity in PHP

I vaguely remember, starting with the first readings of PHP documents (more than 10 years ago) that syntax like an array for accessing characters in arrays ( $string[0] ) caused some ambiguity or undefined behavior.

The O'Reilly PHP Pocket Guide (2nd ed) states:

To solve the problem of ambiguity between strings and arrays, a new syntax was introduced to dereference individual characters from strings:

$string{2}

This syntax is equivalent to $string[2] and is preferred.

I understand that $string[2] can be confusing, but I'm not sure how this can be ambiguous?

Also: I'm curious how the new $string{2} syntax removes ambiguity / confusion, given that curly braces ( obviously ) also work for "real" arrays.

+4
source share
3 answers

The only ambiguity is that if you expect an array, but actually have a string, $var[0] will provide you with the first byte of the string instead of the first element of the array. This can lead to a big crash in the head and wonder why PHP gives you only the first character and not the whole array. This is even more true for non-numeric indices like $var['foo'] , which actually works if $var is a string (yes, please don't ask). That is, it can make debugging a little more difficult if your program is primarily faulty.

There is no ambiguity for proper programs, since a variable cannot be a string and an array at the same time.

+6
source

Many problems caused by the ambiguity between line offsets and array offsets have been removed with the changes in 5.4, which are after the publication date of your link. http://php.net/manual/en/migration54.incompatible.php

For this reason, I recommend [] for line offsets in new code.

+2
source

Well, I checked some variables with this code:

 <pre><?php dumpling(array("php")); dumpling(array()); dumpling(0); dumpling(1); dumpling(TRUE); dumpling(FALSE); dumpling(NULL); dumpling("php"); function dumpling($var){ var_dump($var[0]); var_dump($var{0}); } ?> 

and there was no difference between them.

The output was:

 string(3) "php" string(3) "php" NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL NULL string(1) "p" string(1) "p" 
+1
source

Source: https://habr.com/ru/post/1410932/


All Articles