php 数组实现
数组基础操作
在PHP中,数组是一种灵活的数据结构,可以存储多个值。数组分为索引数组和关联数组两种类型。
索引数组使用数字作为键名:
$fruits = array("Apple", "Banana", "Orange");
// 或简写形式
$fruits = ["Apple", "Banana", "Orange"];
关联数组使用字符串作为键名:
$person = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
数组访问与修改
访问数组元素通过键名实现:
echo $fruits[0]; // 输出 "Apple"
echo $person["name"]; // 输出 "John"
修改数组元素:
$fruits[1] = "Mango";
$person["age"] = 31;
常用数组函数
array_push() 向数组末尾添加元素:
array_push($fruits, "Grape");
// 等同于
$fruits[] = "Grape";
array_pop() 移除并返回数组最后一个元素:
$lastFruit = array_pop($fruits);
array_merge() 合并数组:
$combined = array_merge($array1, $array2);
count() 获取数组长度:
$length = count($fruits);
多维数组实现
PHP支持多维数组,即数组中包含其他数组:
$employees = array(
array("name" => "John", "age" => 30),
array("name" => "Jane", "age" => 25)
);
访问多维数组:
echo $employees[0]["name"]; // 输出 "John"
数组遍历方法
使用foreach循环遍历数组:
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
foreach ($person as $key => $value) {
echo "$key: $value\n";
}
使用for循环遍历索引数组:
for ($i = 0; $i < count($fruits); $i++) {
echo $fruits[$i] . "\n";
}
数组排序
sort() 对数组进行升序排序:
sort($fruits);
rsort() 对数组进行降序排序:
rsort($fruits);
asort() 根据关联数组的值升序排序:
asort($person);
ksort() 根据关联数组的键升序排序:
ksort($person);
数组过滤与搜索
array_filter() 过滤数组元素:
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
in_array() 检查值是否存在:
if (in_array("Apple", $fruits)) {
echo "Found Apple";
}
array_search() 搜索值并返回键名:
$key = array_search("Banana", $fruits);






