leonbloy
leonbloy

Reputation: 75926

string - array ambiguity in PHP

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.

Upvotes: 4

Views: 551

Answers (3)

deceze
deceze

Reputation: 522155

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.

Upvotes: 6

Removed
Removed

Reputation: 1

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

For this reason, I'd reccomend [] for string offsets in new code.

Upvotes: 2

Taha Paksu
Taha Paksu

Reputation: 15616

Well, I have tested 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 didn't seem to be any difference between those two.

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"

Upvotes: 1

Related Questions