Skippy le Grand Gourou
Skippy le Grand Gourou

Reputation: 7704

Double quoted nested array won't work

Consider this :

$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';

This works fine:

php > echo $c[$b[$a]];
w

This also works:

php > echo '$c[$b[$a]]';
'$c[$b[$a]]'

However this leads to a syntax error:

php > echo "$c[$b[$a]]";

PHP Parse error: syntax error, unexpected '[', expecting ']'

While a shorter version works:

php > echo "$b[$a]";
v

Why?

Upvotes: 1

Views: 52

Answers (2)

miken32
miken32

Reputation: 42714

In a double quoted string there are two kinds of variable parsing, simple and complex. Simple parsing will only work with a single dimensional array or object. So these will work:

echo "Valid: $foo[1]";
echo "Valid: $foo[bar]";
echo "Valid: $foo->bar";

But these will not:

echo "Invalid: $foo[1][2]";
echo "Invalid: $foo->bar->baz";
echo "Invalid: $foo->bar()[2]";

Complex parsing is what halfer suggested in his answer, which wraps the expression in curly braces, and will indeed solve your problem:

echo "Valid: ${foo[1][2]}";
echo "Valid: ${foo->bar->baz}";
echo "Valid: ${foo->bar()[2]}";

Upvotes: 3

halfer
halfer

Reputation: 20439

The short answer is: don't write PHP like this! If it is confusing to read then use an intermediate variable.

However, it can be fixed: it looks like PHP just wants the brace delimiters at the outermost edges of the variable:

<?php
$a = 'u';
$b[$a] = 'v';
$c[$b[$a]] = 'w';

echo "{$c[$b[$a]]}";

This is also fine as well:

echo "${c[$b[$a]]}";

In the first case, the whole thing is wrapped in braces, and in the second, the $ is allowed outside of the brace construct to say that the next bit is a variable.

Upvotes: 3

Related Questions