PHP: Access Array Value on the Fly PHP: Access Array Value on the Fly php php

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.


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


I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:

$variable = array('a','b','c');echo $variable[$key];unset($variable);

Or, you could write a small function:

function indexonce(&$ar, $index) {  return $ar[$index];}

and call this with:

$something = indexonce(array('a', 'b', 'c'), 2);

The array should be destroyed automatically now.