In PHP, a normal array subscript must be a fixedly defined string or number, not a variable.
For example, the following code is incorrect:
$index = 'name'; $array = []; $array[$index] = 'John';
In the above example, the error "Undefined index" will be prompted because there is no index in the array $array
An index named $index
exists.
The way to solve this problem is to use the variable as the value of the subscript by {}
. For example:
$index = 'name'; $array = []; $array[$index] = 'John'; $array2 = []; $array2["{$index}"] = 'John';
The above code will work fine, they will both have 'John'
as $array
and $array2
in the array"name"
The value of this subscript.
In addition to the above methods, there is another way to use variables as subscripts, that is to use variable variable
, by using the variable name as the value of another variable and adding before the variable name $
symbols to reference variables. For example:
$index = 'name'; $$index = 'John'; echo $name;
In the above code, dynamic variable definition and use are implemented. $$index
can be seen as the abbreviation of $name
, which will be assigned the value 'John'
, and echo $name
will output 'John'
.
Although variable variable
can make a program more dynamic, it can also make the code difficult to understand and maintain, so it should be used with caution.
In short, array subscripts in PHP cannot use variables, and variables can be used as the value of the subscript through {}
or variable variable
.
The above is the detailed content of Can't variables be used for php array subscripts?. For more information, please follow other related articles on the PHP Chinese website!