Home > Article > Backend Development > Why Can't I Access Array Values Using Expressions in PHP?
Dynamic Array Access in PHP [Original: Access Array Value on the Fly]
PHP provides the ability to access array values using bracket notation ([]). However, a common pain point is the inability to achieve this directly when working with expressions.
Problem:
In the following example, attempting to access an array value using an expression within bracket notation results in an error:
echo array('a', 'b', 'c')[$key];
Solution:
The reason for this error is a limitation in PHP's grammar. Subscript notation is only valid for variable expressions, not general expressions. To overcome this, you can use an intermediary variable:
$variable = array('a', 'b', 'c'); echo $variable[$key];
Technical Explanation:
PHP's grammar does not allow subscript notation on expressions. This means that you cannot apply it to the result of a function call, parentheses, or other expressions. This behavior differs from other languages where it is possible to resolve subscripts against expressions.
Additional Examples of Invalid Subscripts:
$x = array(1, 2, 3); print ($x)[1]; // Invalid: Subscripted expression is a parenthetical expression. function ret($foo) { return $foo; } echo ret($x)[1]; // Invalid: Subscripted expression is a call expression.
The above is the detailed content of Why Can't I Access Array Values Using Expressions in PHP?. For more information, please follow other related articles on the PHP Chinese website!