In PHP, array is a very important data type. It allows you to organize multiple values together and make them easily accessible and operable. In this article, we will explore how to create PHP arrays, including the following:
// 使用 array() 函数 $array1 = array(value1, value2, value3, ...); // 使用 [] 运算符 $array2 = [value1, value2, value3, ...];
Where, value1, value2, value3, ... are the elements of the array. In an array, elements can be any type of value, including numbers, strings, Boolean values, objects, etc.
// 使用 array() 函数创建索引数组 $numbers1 = array(1, 2, 3, 4, 5); // 使用 [] 运算符创建索引数组 $numbers2 = [1, 2, 3, 4, 5];
In the above example, $numbers1 and $numbers2 are both index arrays containing 5 elements. You can access elements in an array by index, as shown below:
echo $numbers1[0]; // 输出 1 echo $numbers2[2]; // 输出 3
// 使用 array() 函数创建关联数组 $colors1 = array("red" => "#ff0000", "green" => "#00ff00", "blue" => "#0000ff"); // 使用 [] 运算符创建关联数组 $colors2 = ["red" => "#ff0000", "green" => "#00ff00", "blue" => "#0000ff"];
In the above example, $colors1 and $colors2 are both associative arrays containing 3 elements. You can access the elements in the array by key, as shown below:
echo $colors1["red"]; // 输出 #ff0000 echo $colors2["blue"]; // 输出 #0000ff
// 添加元素 $fruits = ["apple", "banana"]; $fruits[] = "orange"; // 将 "orange" 添加到数组尾部 $fruits[3] = "grape"; // 将 "grape" 添加到索引为 3 的位置 // 删除元素 unset($fruits[1]); // 删除索引为 1 的元素,即 "banana" // 修改元素 $fruits[0] = "pear"; // 将索引为 0 的元素修改为 "pear" // 获取数组长度 $count = count($fruits); // $count 的值为 3
// 使用 for 循环遍历索引数组 for ($i = 0; $i < count($fruits); $i++) { echo $fruits[$i] . " "; } // 输出:pear orange grape // 使用 foreach 循环遍历关联数组 foreach ($colors2 as $key => $value) { echo $key . ": " . $value . " "; } // 输出:red: #ff0000 green: #00ff00 blue: #0000ff
// 添加元素 array_push($fruits, "kiwi"); // 将 "kiwi" 添加到数组尾部 array_unshift($fruits, "cherry"); // 将 "cherry" 添加到数组头部 // 删除元素 array_pop($fruits); // 删除数组尾部的元素 array_shift($fruits); // 删除数组头部的元素 // 排序 sort($fruits); // 对数组进行升序排序 rsort($fruits); // 对数组进行降序排序
Summary
Array is a very useful data type that can organize multiple values together and provides a variety of methods to operate elements. . In PHP, we can use the array() function or [] operator to create arrays. We can create indexed arrays and associative arrays. When manipulating arrays, you can use built-in array functions to handle arrays more conveniently.
The above is the detailed content of How to create php array. For more information, please follow other related articles on the PHP Chinese website!