数组操作 #

一、添加元素 #

1.1 末尾添加 #

php
<?php
$fruits = ['apple', 'banana'];

$fruits[] = 'cherry';
array_push($fruits, 'date', 'elderberry');

print_r($fruits);

1.2 开头添加 #

php
<?php
$fruits = ['banana', 'cherry'];

array_unshift($fruits, 'apple');

print_r($fruits);

1.3 指定位置添加 #

php
<?php
$fruits = ['apple', 'cherry', 'date'];

array_splice($fruits, 1, 0, 'banana');

print_r($fruits);

1.4 添加关联元素 #

php
<?php
$user = ['name' => 'John'];

$user['age'] = 25;
$user['city'] = 'Beijing';

print_r($user);

二、删除元素 #

2.1 删除指定元素 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

unset($fruits[1]);
print_r($fruits);

2.2 删除末尾元素 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

$last = array_pop($fruits);
echo "Removed: $last\n";
print_r($fruits);

2.3 删除开头元素 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

$first = array_shift($fruits);
echo "Removed: $first\n";
print_r($fruits);

2.4 删除指定范围 #

php
<?php
$fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];

$removed = array_splice($fruits, 1, 2);
echo "Removed: ";
print_r($removed);
print_r($fruits);

2.5 删除所有元素 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

$fruits = [];
unset($fruits);

$fruits = ['apple', 'banana', 'cherry'];
$fruits = array_diff($fruits, $fruits);

三、修改元素 #

3.1 直接修改 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

$fruits[1] = 'blueberry';
print_r($fruits);

3.2 批量修改 #

php
<?php
$numbers = [1, 2, 3, 4, 5];

$numbers = array_map(fn($n) => $n * 2, $numbers);
print_r($numbers);

3.3 条件修改 #

php
<?php
$numbers = [1, 2, 3, 4, 5];

$numbers = array_map(function($n) {
    return $n % 2 === 0 ? $n * 2 : $n;
}, $numbers);

print_r($numbers);

3.4 替换元素 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

array_splice($fruits, 1, 1, 'blueberry');
print_r($fruits);

四、查找元素 #

4.1 检查键存在 #

php
<?php
$user = ['name' => 'John', 'age' => 25];

var_dump(isset($user['name']));
var_dump(array_key_exists('name', $user));
var_dump(isset($user['email']));

4.2 检查值存在 #

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

var_dump(in_array('banana', $fruits));
var_dump(in_array('Banana', $fruits));
var_dump(in_array('Banana', $fruits, true));

4.3 查找键名 #

php
<?php
$fruits = ['apple', 'banana', 'cherry', 'banana'];

$key = array_search('banana', $fruits);
echo $key;

$keys = array_keys($fruits, 'banana');
print_r($keys);

4.4 查找所有匹配键 #

php
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$evenKeys = array_keys(array_filter($numbers, fn($n) => $n % 2 === 0));
print_r($evenKeys);

五、数组切片 #

5.1 array_slice #

php
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$slice = array_slice($numbers, 2, 4);
print_r($slice);

$slice = array_slice($numbers, -3);
print_r($slice);

$slice = array_slice($numbers, 2, -2);
print_r($slice);

5.2 保留键名 #

php
<?php
$user = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];

$slice = array_slice($user, 1, 2, true);
print_r($slice);

六、数组合并 #

6.1 array_merge #

php
<?php
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 3, 'c' => 4];

$merged = array_merge($a, $b);
print_r($merged);

$a = [1, 2];
$b = [3, 4];

$merged = array_merge($a, $b);
print_r($merged);

6.2 + 运算符 #

php
<?php
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 3, 'c' => 4];

$merged = $a + $b;
print_r($merged);

6.3 array_replace #

php
<?php
$a = ['a' => 1, 'b' => 2];
$b = ['b' => 3, 'c' => 4];

$replaced = array_replace($a, $b);
print_r($replaced);

6.4 展开运算符 #

php
<?php
$a = [1, 2];
$b = [3, 4];

$merged = [...$a, ...$b];
print_r($merged);

七、数组分割 #

7.1 array_chunk #

php
<?php
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

$chunks = array_chunk($numbers, 3);
print_r($chunks);

$chunks = array_chunk($numbers, 3, true);
print_r($chunks);

7.2 分页应用 #

php
<?php
$items = range(1, 100);
$page = 2;
$perPage = 10;

$offset = ($page - 1) * $perPage;
$pageItems = array_slice($items, $offset, $perPage);

print_r($pageItems);

八、数组填充 #

8.1 array_fill #

php
<?php
$arr = array_fill(0, 5, 'hello');
print_r($arr);

$arr = array_fill(3, 3, 'world');
print_r($arr);

8.2 array_pad #

php
<?php
$arr = [1, 2, 3];

$padded = array_pad($arr, 5, 0);
print_r($padded);

$padded = array_pad($arr, -5, 0);
print_r($padded);

九、数组去重 #

9.1 array_unique #

php
<?php
$numbers = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];

$unique = array_unique($numbers);
print_r($unique);

9.2 关联数组去重 #

php
<?php
$users = [
    ['id' => 1, 'name' => 'John'],
    ['id' => 2, 'name' => 'Jane'],
    ['id' => 1, 'name' => 'John']
];

$unique = array_unique($users, SORT_REGULAR);
print_r($unique);

十、实际应用 #

10.1 购物车 #

php
<?php
class Cart
{
    private array $items = [];
    
    public function add(int $productId, int $quantity = 1): void
    {
        if (isset($this->items[$productId])) {
            $this->items[$productId]['quantity'] += $quantity;
        } else {
            $this->items[$productId] = [
                'product_id' => $productId,
                'quantity' => $quantity
            ];
        }
    }
    
    public function remove(int $productId): void
    {
        unset($this->items[$productId]);
    }
    
    public function update(int $productId, int $quantity): void
    {
        if ($quantity <= 0) {
            $this->remove($productId);
        } else {
            $this->items[$productId]['quantity'] = $quantity;
        }
    }
    
    public function getItems(): array
    {
        return $this->items;
    }
    
    public function getTotal(): int
    {
        return array_sum(array_column($this->items, 'quantity'));
    }
}

10.2 数据过滤 #

php
<?php
function filterByStatus(array $items, string $status): array
{
    return array_filter($items, fn($item) => $item['status'] === $status);
}

$orders = [
    ['id' => 1, 'status' => 'pending'],
    ['id' => 2, 'status' => 'completed'],
    ['id' => 3, 'status' => 'pending']
];

$pending = filterByStatus($orders, 'pending');
print_r($pending);

10.3 数据分组 #

php
<?php
function groupBy(array $items, string $key): array
{
    $grouped = [];
    
    foreach ($items as $item) {
        $groupKey = $item[$key];
        $grouped[$groupKey][] = $item;
    }
    
    return $grouped;
}

$users = [
    ['name' => 'John', 'city' => 'Beijing'],
    ['name' => 'Jane', 'city' => 'Shanghai'],
    ['name' => 'Bob', 'city' => 'Beijing']
];

$byCity = groupBy($users, 'city');
print_r($byCity);

十一、总结 #

本章学习了:

  • 添加元素:array_push、array_unshift
  • 删除元素:unset、array_pop、array_shift
  • 修改元素:直接赋值、array_map
  • 查找元素:in_array、array_search
  • 数组切片:array_slice
  • 数组合并:array_merge、+、展开运算符
  • 数组分割:array_chunk
  • 数组去重:array_unique

下一章将学习数组遍历。

最后更新:2026-03-26