PHP数组操作完整指南:增删改查
PHP数组是一种非常灵活的数据结构,可以存储多个值。以下是PHP数组的增删改查操作完整指南。
一、创建数组
// 索引数组
$fruits = array("Apple", "Banana", "Orange");
// 或简写形式
$fruits = ["Apple", "Banana", "Orange"];
// 关联数组
$person = [
"name" => "John",
"age" => 30,
"city" => "New York"
];
二、增加元素
1. 索引数组
// 在末尾添加元素
$fruits[] = "Mango";
array_push($fruits, "Grape", "Peach");
// 在开头添加元素
array_unshift($fruits, "Pineapple");
2. 关联数组
$person["email"] = "john@example.com";
3. 合并数组
$vegetables = ["Carrot", "Broccoli"];
$allFoods = array_merge($fruits, $vegetables);
三、删除元素
1. 索引数组
// 删除最后一个元素
array_pop($fruits);
// 删除个元素
array_shift($fruits);
// 删除指定位置的元素
unset($fruits[1]); // 注意:这会保留索引,可能导致非连续索引
$fruits = array_values($fruits); // 重新索引
2. 关联数组
unset($person["age"]);
3. 删除多个元素
$removed = array_splice($fruits, 1, 2); // 从索引1开始删除2个元素
四、修改元素
1. 索引数组
$fruits[0] = "Strawberry";
2. 关联数组
$person["name"] = "John Doe";
3. 批量修改
$fruits = array_map(function($item) {
return strtoupper($item);
}, $fruits);
五、查询元素
1. 获取单个元素
echo $fruits[0]; // 索引数组
echo $person["name"]; // 关联数组
2. 检查元素是否存在
// 索引数组
if (isset($fruits[2])) {
echo "存在";
}
// 关联数组
if (array_key_exists("age", $person)) {
echo "存在";
}
// 检查值是否存在
if (in_array("Apple", $fruits)) {
echo "存在";
}
3. 搜索元素
$key = array_search("Banana", $fruits); // 返回键名或false
4. 遍历数组
// 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";
}
六、其他常用操作
1. 数组长度
$count = count($fruits);
2. 排序
sort($fruits); // 升序
rsort($fruits); // 降序
asort($person); // 按值排序关联数组
ksort($person); // 按键排序关联数组
3. 过滤
$numbers = [1, 2, 3, 4, 5];
$even = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
4. 数组切片
$someFruits = array_slice($fruits, 1, 2); // 从索引1开始取2个元素
5. 多维数组操作
$users = [
["name" => "John", "age" => 30],
["name" => "Jane", "age" => 25]
];
// 获取所有用户名
$names = array_column($users, "name");
// 查找特定用户
$jane = array_filter($users, function($user) {
return $user["name"] === "Jane";
});
七、注意事项
- 使用
unset()
删除元素后,索引不会重新排列,可以使用array_values()
重置索引 isset()
和array_key_exists()
的区别:前者还会检查值是否为null- 对于大型数组,考虑使用生成器或特定算法提高性能
- PHP 7.4+支持数组解构:
[$a, $b] = $array
掌握这些数组操作技巧,可以让你在PHP开发中更加得心应手!
(本文来源:nzw6.com)