PHP 数组函数大全:50个常用函数一文搞懂

小飞兽 PHP 16 次阅读 2026-07-16

为什么数组函数重要

PHP项目里数组无处不在。一个经验法则是:能用数组函数解决的,绝不要手写循环。代码更短、更安全、也更易读。

一、创建数组

1. array() / 短数组语法

$arr = array(1, 2, 3, 4, 5);
$arr = [1, 2, 3, 4, 5]; // PHP 7.1+

2. range()

快速生成连续数字或字母序列:

$nums = range(1, 10);       // [1,2,3,4,5,6,7,8,9,10]
$letters = range('a', 'z'); // ['a','b',...'z']
$evens = range(0, 10, 2);   // [0,2,4,6,8,10]

3. array_fill()

$arr = array_fill(0, 5, '默认');
// ['默认', '默认', '默认', '默认', '默认']

二、遍历数组

4. foreach()

$users = ['name' => '张三', 'age' => 25, 'city' => '绍兴'];
foreach ($users as $key => $value) {
    echo "$key: $value\n";
}

三、排序函数

5. sort() / rsort()

sort升序,rsort降序,改变原数组并丢失键名:

$scores = [85, 72, 96, 61, 78];
sort($scores);    // [61,72,78,85,96]
rsort($scores);   // [96,85,78,72,61]

6. asort() / arsort()

保持键值关联的排序,适合关联数组:

$prices = ['苹果'=>3.5, '香蕉'=>2.0, '橙子'=>4.8];
asort($prices);
// ['香蕉'=>2.0, '苹果'=>3.5, '橙子'=>4.8]

7. ksort() / krsort() 按键名排序

ksort($prices);  // 升序
krsort($prices); // 降序

8. usort() 自定义排序

$users = [['name'=>'张三','age'=>25], ['name'=>'李四','age'=>20]];
usort($users, fn($a,$b) => $a['age'] <=> $b['age']);
// 按age升序

四、搜索与过滤

9. in_array()

$roles = ['admin', 'editor', 'author'];
if (in_array('admin', $roles)) {
    echo '是管理员';
}
// 严格模式(类型也要一致)
in_array('1', [1,2,3], true); // false

10. array_search() 查找键名

$colors = ['red'=>'红色', 'blue'=>'蓝色', 'green'=>'绿色'];
$key = array_search('蓝色', $colors); // 'blue'

11. array_filter() 过滤

$nums = [1,2,3,4,5,6,7,8,9,10];
$evens = array_filter($nums, fn($n) => $n % 2 === 0);
// [2,4,6,8,10]

$values = ['苹果', '', '香蕉', null, '橙子'];
$filled = array_filter($values, fn($v) => !empty($v));
// ['苹果', '香蕉', '橙子']


五、转换与映射


12. array_map() 对每个元素操作


$prices = [29.9, 49.9, 99.9];
$rounded = array_map('round', $prices); // [30, 50, 100]
$labels = array_map(fn($p) => '¥' . number_format($p, 2), $prices);
// ['¥29.90', '¥49.90', '¥99.90']

13. array_column() 提取列


$users = [
['name'=>'张三', 'score'=>92],
['name'=>'李四', 'score'=>85],
];
$names = array_column($users, 'name'); // ['张三', '李四']

14. array_keys() / array_values()


$config = ['host'=>'localhost', 'port'=>3306];
$keys = array_keys($config); // ['host', 'port']
$values = array_values($config); // ['localhost', 3306]

六、合并与拆分


15. array_merge() 合并


$a = ['a'=>1, 'b'=>2];
$b = ['b'=>3, 'c'=>4];
$result = array_merge($a, $b); // ['a'=>1, 'b'=>3, 'c'=>4]

16. array_slice() 截取


$items = ['苹果', '香蕉', '橙子', '葡萄', '西瓜'];
$slice = array_slice($items, 1, 2); // ['香蕉', '橙子']
$last3 = array_slice($items, -3); // ['橙子', '葡萄', '西瓜']

17. array_chunk() 拆分


$ids = [1,2,3,4,5,6,7,8,9];
$chunks = array_chunk($ids, 3);
// [[1,2,3], [4,5,6], [7,8,9]]

七、统计与计算


18. count() 统计元素


$arr = [1,2,3,[4,5,6]];
count($arr); // 4
count($arr, COUNT_RECURSIVE); // 7(含嵌套)

19. array_sum() / array_product()


$prices = [29.9, 49.9, 19.9];
array_sum($prices); // 99.7
$numbers = [2,3,4,5];
array_product($numbers); // 120

20. array_reduce() 归纳为单一值


$orders = [
['product'=>'iPhone', 'amount'=>6999],
['product'=>'MacBook', 'amount'=>9999],
];
$total = array_reduce($orders, fn($sum, $o) => $sum + $o['amount'], 0);
// 18497

八、其他高频函数


21. array_key_exists() 检查键


$data = ['name'=>'张三', 'age'=>25];
array_key_exists('name', $data); // true

22. array_unique() 去重


$scores = [85, 72, 96, 72, 85];
array_unique($scores); // [85, 72, 96]

23. array_reverse() 反转


$arr = [1,2,3,4,5];
array_reverse($arr, true); // 保持键名

24. shuffle() 随机打乱


$cards = ['A','2','3','J','Q','K'];
shuffle($cards); // 洗牌(改变原数组)

25. array_rand() 随机键名


$prizes = ['一等奖', '二等奖', '谢谢参与'];
$win = $prizes[array_rand($prizes)];

26. compact() / extract()


$name = '张三'; $age = 25;
$data = compact('name', 'age'); // ['name'=>'张三','age'=>25]

实战技巧


分页


$all = range(1, 100);
$page = max(1, (int)($_GET['page'] ?? 1));
$items = array_slice($all, ($page-1)*10, 10);

去重后统计


$visits = ['北京', '上海', '北京', '上海', '北京'];
$cityCount = array_count_values($visits);
// ['北京'=>3, '上海'=>2]

二维数组排序


$products = [
['name'=>'iPhone', 'price'=>6999],
['name'=>'小米', 'price'=>2999],
];
usort($products, fn($a,$b) => $a['price'] <=> $b['price']);

总结



    • 能用内置函数的,绝不手写循环

    • 注意是否改变原数组(sort/array_filter/shuffle会改)

    • 箭头函数(fn())配合array_map/array_filter/array_reduce让代码极度简洁

  • array_column + array_sum是处理二维数组的黄金组合