Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Access Array Value on the Fly

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

like image 305
Pierre Spring Avatar asked Aug 16 '08 12:08

Pierre Spring


People also ask

How do you access content of an array?

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

What does => mean in PHP array?

It means assign the key to $user and the variable to $pass. When you assign an array, you do it like this. $array = array("key" => "value"); It uses the same symbol for processing arrays in foreach statements. The '=>' links the key and the value.

What does In_array return in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.


1 Answers

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. 
like image 86
John Douthat Avatar answered Oct 09 '22 09:10

John Douthat