PHP: Access Array Value on the Fly

The technical answer is that the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages. I’ve always viewed it as a deficiency in the language, because it is possible to have a grammar that resolves subscripts against any expression unambiguously. It could be the case, however, that they’re using an inflexible parser generator or they simply don’t want to break some sort of backwards compatibility.

Here are a couple more examples of invalid subscripts on valid expressions:

$x = array(1,2,3);
print ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.

function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, on a call expression, not a variable exp.

Leave a Comment