in php, i often need to map a variable using an array ... but i can not seem to be able to do this in a one liner. c.f. example:

// the following results in an error:
echo array('a','b','c')[$key];

// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];

this is a minor problem, but it keeps bugging every once in a while ... i don't like the fact, that i use a variable for nothing ;)

+3  A: 

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];

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.


@onnodb: that is precisely the thing i am trying to avoid ;)

e.g. i often need the first item in a returned array, then i just do:


i just cannot believe there isn't a way to get the same thing for any $key ... i think my question is more related to style, than pure performance ...

Pierre Spring
+2  A: 

@brian-warshaw: afaik the following is very well possible in php:

Pierre Spring
// the following results in an error:
echo array('a','b','c')[$key];

I SO wish PHP could do this...I completely sympathize with you.

This doesn't work either, unfortunately:


Actually, it does. Just make each method return $this. On the other can't do this:

$obj = new Object()->method();

Which is something else on my wishlist.

+9  A: 

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 the case 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, inside a parenthetical expression, not a variable

function ret($foo) { return $foo; }
echo ret($x)[1]; // illegal, inside a call expression, not a variable
John Douthat
There was a change proposal at least for the second syntax, but it was rejected:
Status is now changed to accepted

Or something like this, if you need the array value in a variable

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


actually, there is an elegant solution:) The following will assign the 3rd element of the array returned by myfunc to $myvar:

$myvar = array_shift(array_splice(myfunc(),2));
John Smith