Home  >  Article  >  Backend Development  >  How to declare php array key

How to declare php array key

王林
王林Original
2023-05-11 09:23:06382browse

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.

  1. Declare arrays directly

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.

  1. Use the array function

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 =>.

  1. Dynamicly add elements

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!

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