Home >Backend Development >PHP Tutorial >PHP array introductory tutorial: how to create, traverse and manipulate arrays
PHP array is a powerful and flexible data structure. This article will introduce how to create, traverse and operate PHP arrays for beginners.
1. Create a PHP array
In PHP, an array is an ordered collection composed of a set of key-value pairs. You can create an array in the following two ways:
$array = array('name' => '小明', 'age' => 18, 'gender' =>'男');
In the above code, $array
represents an array variable, which contains There are three elements, namely name, age and gender. Each element consists of a key name and a key value. The key name is represented by a string, and the key value can be any type of data.
$array[0] = 'apple'; $array[1] = 'orange'; $array[2] = 'banana';
In the above code, the $array
array contains three elements, They are 'apple', 'orange' and 'banana' respectively, and their key names are 0, 1 and 2 respectively.
2. Traverse PHP arrays
In PHP, we can use the foreach loop to traverse arrays. The example is as follows:
foreach ($array as $key => $value) { echo "键名:".$key.",键值:".$value."<br>"; }
In the above code, $array
represents the array we want to traverse, $key
represents the key name of the element currently looped to, $value
represents the key value of the current element.
3. Manipulate PHP arrays
You can use square brackets plus the key name of the element to get an element in the array The value of Change the value of the 'name' element in the array to '小红'.
Use the unset function to delete an element in the array. The example is as follows:
echo $array['name']; // 输出:小明Add array element
$array['name'] = '小红';
The above code adds a new element and a new element value to the array respectively. The key name of the first element is 'address' and the key value is 'Beijing City'. Since the second element does not display a specified key name, the system will automatically assign it a serial number as the key name.
The above is the detailed content of PHP array introductory tutorial: how to create, traverse and manipulate arrays. For more information, please follow other related articles on the PHP Chinese website!