PHP: Access Array Value on the Fly

Solution 1:

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.

Solution 2:

This is called array dereferencing. It has been added in php 5.4. http://www.php.net/releases/NEWS_5_4_0_alpha1.txt

update[2012-11-25]: as of PHP 5.5, dereferencing has been added to contants/strings as well as arrays