Home  >  Article  >  Backend Development  >  How to Access Array Values with Variables in a Single PHP Line?

How to Access Array Values with Variables in a Single PHP Line?

Barbara Streisand
Barbara StreisandOriginal
2024-11-20 01:13:03146browse

How to Access Array Values with Variables in a Single PHP Line?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn