PHP中的数组函数学习
在PHP中,有许多内置的函数可以用于操作和处理数组。这些函数可以创建数组,对数组进行分析,对数组元素进行查找和排序等。
- array() 创建数组
$array = array("size" => "XL", "color" => "gold");
- count() 计算数组中的元素数量
$array = array("size" => "XL", "color" => "gold");
echo count($array); // 输出: 2
- array\_push() 将一个或多个元素推入数组的末尾
$array = array("size" => "XL", "color" => "gold");
array_push($array, "brand", "nike");
print_r($array); // 输出: Array ( [size] => XL [color] => gold [0] => brand [1] => nike )
- array\_pop() 移除数组的最后一个元素
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
array_pop($array);
print_r($array); // 输出: Array ( [size] => XL [color] => gold )
- array\_shift() 移除数组的第一个元素
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
array_shift($array);
print_r($array); // 输出: Array ( [color] => gold [brand] => nike )
- array\_unshift() 在数组的开始处插入一个或多个元素
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
array_unshift($array, "new");
print_r($array); // 输出: Array ( [0] => new [size] => XL [color] => gold [brand] => nike )
- array\_values() 返回数组的所有值,并自动为每个值分配一个新的整数索引
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
print_r(array_values($array)); // 输出: Array ( [0] => XL [1] => gold [2] => nike )
- array\_keys() 返回数组中所有的键名
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
print_r(array_keys($array)); // 输出: Array ( [0] => size [1] => color [2] => brand )
- in\_array() 检查数组中是否存在某个值
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
if (in_array("gold", $array)) {
echo "gold exists"; // 输出: gold exists
}
- array\_search() 在数组中搜索某个键值,如果成功则返回键名
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
echo array_search("gold", $array); // 输出: color
- array\_reverse() 将数组中的元素顺序颠倒
$array = array("size" => "XL", "color" => "gold", "brand" => "nike");
print_r(array_reverse($array)); // 输出: Array ( [brand] => nike [color] => gold [size] => XL )
- array\_unique() 移除数组中重复的值
$array = array("
评论已关闭