Richard Pérez
Richard Pérez

Reputation: 1487

PHP variable Interpolation, why it works

Given this setup

$names = array('Smith', 'Jones', 'Jackson');

I understand that this works:

echo "Citation: {$names[1]}[1987]".PHP_EOL; //Citation: Jones[1987]

PHP through the complex syntax with curly braces, is pulling the value of the second element on the array and the [1987] is just another text...

But in the next code:

echo "Citation: $names[1][1987]".PHP_EOL;

I'd expect an error, I'd expect PHP interprets it as a two dimensional array and thrown an error, but instead it gave me same output that the code above "Citation: Jones[1987]"

Why is that?

Upvotes: 1

Views: 305

Answers (1)

Rizier123
Rizier123

Reputation: 59701

PHP goes here for the first occurrence of ], since you have an array, as you can see in the manual:

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

This means the end is the first index, e.g.

echo "Citation: $names[1][1987]".PHP_EOL;
              //^ Start ^ End

So that means your "second dimension" is just parsed as a normal string. So for more complex structures you have to use the complex syntax to mark the start and the end of your variable, e.g.

echo "Citation: {$names[1][1987]}".PHP_EOL;
              //^ See here      ^

So this will give you the warning:

Notice: Uninitialized string offset: 1987

Upvotes: 1

Related Questions