Home > Article > Backend Development > There are several ways to use arrays in php
In PHP language, array is a widely used data structure, used to store list-like data, providing convenient and flexible usage. Arrays in PHP can be divided into the following ways:
Indexed array is the simplest and most commonly used array type in PHP. It consists of an ordered sequence of elements, each with a unique numerical index. In PHP, indexing starts at 0 and increases until the last element. An index array can be created in the following way:
$names = array("Tom", "John", "Mary", "Lily"); // 或者 $names = ["Tom", "John", "Mary", "Lily"];
where the variable $names is an index array containing 4 elements. It accesses array elements by numerical index, for example:
echo $names[0]; // 输出 "Tom" echo $names[1]; // 输出 "John" echo $names[2]; // 输出 "Mary" echo $names[3]; // 输出 "Lily"
Associative array is another common array type in PHP. It consists of an unordered set of elements, each element has a unique key value. In PHP, this key value can be any legal string, including numbers and letters. You can create an associative array in the following way:
$ages = array("Tom" => 18, "John" => 22, "Mary" => 25, "Lily" => 20); // 或者 $ages = ["Tom" => 18, "John" => 22, "Mary" => 25, "Lily" => 20];
where the variable $ages is an associative array containing 4 elements. It accesses array elements by key value, for example:
echo $ages["Tom"]; // 输出 18 echo $ages["John"]; // 输出 22 echo $ages["Mary"]; // 输出 25 echo $ages["Lily"]; // 输出 20
The key value of an associative array is usually a string, but it can also be an integer or other basic data type.
Multidimensional array means that one array contains another array. In PHP, you can create multidimensional arrays using indexed arrays or associative arrays. The following is an example:
$student_scores = array( "Tom" => array("Math" => 80, "English" => 90), "John" => array("Math" => 75, "English" => 85), "Mary" => array("Math" => 85, "English" => 95) );
Among them, the variable $student_scores is an associative array containing 3 elements, and each element is an associative array containing 2 elements. You can use nested key values to access the elements of multi-dimensional arrays, for example:
echo $student_scores["Tom"]["Math"]; // 输出 80 echo $student_scores["John"]["English"]; // 输出 85 echo $student_scores["Mary"]["Math"]; // 输出 85
The above are the three main ways of arrays in PHP. At the same time, PHP also provides some advanced array functions, such as array_merge(), array_unique(), array_search(), etc. These functions can process array data more flexibly and improve program efficiency and performance.
The above is the detailed content of There are several ways to use arrays in php. For more information, please follow other related articles on the PHP Chinese website!