In PHP, there are many ways to declare an array. An array is a collection of several elements, each element consists of a key and a value.
When declaring a PHP array, you can declare the keys and values of the array at the same time, or you can only declare the values of the array, and the keys will be automatically assigned. Here are a few possible ways.
You can use the concise syntax of arrays to declare arrays, that is, place the corresponding relationship between keys and values within square brackets.
For example:
$fruits = ['apple' => '红苹果', 'banana' => '香蕉', 'grape' => '葡萄'];
In the above code, the variable $fruits
is an array with three elements, each element consists of a key and a value.
Another commonly used way to declare an array is to use the array function. This function can receive several parameters, each parameter is a value.
You can use the array function like this to declare an array:
$fruits = array('apple' => '红苹果', 'banana' => '香蕉', 'grape' => '葡萄');
It should be noted that when using the array function, the keys and values need to be separated by commas. The corresponding relationship is represented by =>
.
If you need to dynamically add elements when using an array, you can also use $array[]
to add elements.
For example:
$fruits = []; $fruits['apple'] = '红苹果'; $fruits['banana'] = '香蕉'; $fruits['grape'] = '葡萄';
While declaring the $fruits
array, the above code also adds three elements to the array. Each element consists of a key and a value composition. It should be noted that the key name needs to be enclosed in single quotes or double quotes, and the difference between the two is that variables cannot be used in single quotes.
No matter which way you declare the array, you need to specify a unique key name for each key, otherwise key name conflicts will occur. At the same time, the key names of the array can be strings, integers, or other types of data.
The above is the detailed content of How to declare php array key. For more information, please follow other related articles on the PHP Chinese website!