PHP Array Value Accessibility on the Fly
Query:
How can I access an array value using a variable in a single line of PHP code without resorting to an intermediate variable, as demonstrated in the following example:
// Incorrect approach: echo array('a', 'b', 'c')[$key]; // Correct but verbose approach: $variable = array('a', 'b', 'c'); echo $variable[$key];
Response:
According to the PHP language grammar, subscript notation is exclusively applicable to variable expressions, not expressions in general. This is unlike many other programming languages. This limitation can be perceived as a flaw, as it prevents subscripts from being used with any expression without ambiguity.
Consider the following additional examples of invalid subscript usage on valid expressions:
$x = array(1, 2, 3); print ($x)[1]; // Illegal on a parenthesis expression (not a variable expression) function ret($foo) { return $foo; } echo ret($x)[1]; // Illegal on a function call expression (not a variable expression)
The above is the detailed content of How to Access Array Values with Variables in a Single PHP Line?. For more information, please follow other related articles on the PHP Chinese website!