1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks... IMHO it should say "... With array indices, the FIRST closing square bracket (]) marks the end of the index ..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.