Home > Article > Backend Development > PHP array basic knowledge analysis
PHP array basic knowledge analysis
In PHP, array is a very important and commonly used data type, which can store multiple values and retrieve them by index or key. access these values. This article will start from the basics, introduce the use of PHP arrays and some common operations, and provide specific code examples.
In PHP, you can use two methods to create an array: index array and associative array.
The index array is an array that stores values according to numerical index. The index increases from 0. The method of creating an index array is as follows:
// 使用array()函数创建索引数组 $colors = array("Red", "Green", "Blue"); // 使用方括号[]创建索引数组(PHP 5.4及以上版本支持) $numbers = [1, 2, 3];
Associative array is an array that uses key-value pairs to store values. The key name needs to be specified when defining the array elements. The method of creating an associative array is as follows:
// 使用array()函数创建关联数组 $person = array("name" => "Alice", "age" => 30, "city" => "New York"); // 使用方括号[]创建关联数组(PHP 5.4及以上版本支持) $book = ["title" => "PHP Basics", "author" => "John Doe"];
Accessing array elements can be achieved by index or key.
$colors = array("Red", "Green", "Blue"); echo $colors[0]; // 输出:Red echo $colors[1]; // 输出:Green echo $colors[2]; // 输出:Blue
$person = array("name" => "Alice", "age" => 30, "city" => "New York"); echo $person["name"]; // 输出:Alice echo $person["age"]; // 输出:30 echo $person["city"]; // 输出:New York
Traversing the array is for each element in the array To perform operations, a loop structure can be used.
$numbers = [1, 2, 3, 4, 5]; foreach ($numbers as $number) { echo $number . " "; } // 输出:1 2 3 4 5
$person = array("name" => "Alice", "age" => 30, "city" => "New York"); foreach ($person as $key => $value) { echo $key . ": " . $value . "<br>"; } // 输出:name: Alice // 输出:age: 30 // 输出:city: New York
PHP provides a wealth of array functions for To operate on arrays, the following are some commonly used array functions:
count($array)
: Returns the number of array elements. array_push($array, $value)
: Add one or more elements to the end of the array. array_pop($array)
: Removes the element at the end of the array and returns that element. array_shift($array)
: Delete the element at the beginning of the array and return that element. array_unshift($array, $value)
: Add one or more elements to the beginning of the array. The above is a simple analysis of the basic knowledge of PHP arrays. By learning these basic knowledge, you can use arrays to store and operate data more flexibly. I hope this article can help you gain a deeper understanding of the usage of PHP arrays.
The above is the detailed content of PHP array basic knowledge analysis. For more information, please follow other related articles on the PHP Chinese website!