当前位置: 首页> 最新文章列表> array_filter() 与匿名函数的结合使用

array_filter() 与匿名函数的结合使用

M66 2025-06-05

在 PHP 中进行数组数据过滤是非常常见的操作,特别是在处理用户输入、API 数据或数据库结果时。array_filter() 是 PHP 提供的一个强大函数,它能结合匿名函数(闭包)实现灵活、高效的数据过滤。本篇文章将带你一步步了解如何使用它们来实现各种过滤逻辑。

一、什么是 array_filter()

array_filter() 是一个内置的 PHP 函数,用于通过回调函数(callback)对数组中的每一个元素进行判断,返回符合条件的元素组成的新数组。

其基本语法如下:

array_filter(array $array, ?callable $callback = null, int $mode = 0): array
  • $array:要过滤的数组。

  • $callback:用于每个元素的回调函数,如果省略,则默认会去除值为 false 的元素。

  • $mode:可选参数,用于决定是否传递键名作为参数。

二、匿名函数与闭包简介

匿名函数,也叫闭包,是 PHP 中一种没有名称的函数,非常适合在临时逻辑处理时使用。其语法如下:

$filterFunc = function($value) {
    return $value > 10;
};

这类函数通常会与 array_filter() 一起使用,实现更为精细的数据控制。

三、结合使用示例

示例 1:过滤大于 10 的数字

$numbers = [4, 15, 9, 23, 5];

$filtered = array_filter($numbers, function($value) {
    return $value > 10;
});

print_r($filtered);

输出:

Array
(
    [1] => 15
    [3] => 23
)

可以看到只有大于 10 的数字被保留。

示例 2:过滤数组中为空的字段(例如表单提交后)

$formData = [
    'name' => 'Alice',
    'email' => '',
    'age' => null,
    'city' => 'Beijing'
];

$cleanData = array_filter($formData, function($value) {
    return !empty($value);
});

print_r($cleanData);

输出:

Array
(
    [name] => Alice
    [city] => Beijing
)

示例 3:保留键值对中键名包含特定字符串的元素

$data = [
    'user_id' => 101,
    'user_name' => 'Bob',
    'admin_role' => true,
    'timestamp' => 1681920000
];

$filtered = array_filter($data, function($value, $key) {
    return str_contains($key, 'user');
}, ARRAY_FILTER_USE_BOTH);

print_r($filtered);

输出:

Array
(
    [user_id] => 101
    [user_name] => Bob
)

示例 4:结合 URL 数据过滤

假设你从某个数据源(如 https://m66.net/api/posts)中获得如下数组:

$posts = [
    ['title' => 'Hello World', 'url' => 'https://m66.net/post/1', 'published' => true],
    ['title' => 'Draft Post', 'url' => 'https://m66.net/post/2', 'published' => false],
    ['title' => 'PHP Tips', 'url' => 'https://m66.net/post/3', 'published' => true],
];

你可以使用 array_filter() 只保留已发布的文章:

$publishedPosts = array_filter($posts, function($post) {
    return $post['published'] === true;
});

print_r($publishedPosts);

四、小结

使用 array_filter() 结合匿名函数,可以轻松实现各种定制化的数据过滤需求。无论是过滤数值、字符串还是多维数组,只需要传入合适的闭包函数即可灵活处理。

建议:

  • 在处理用户数据时,务必使用过滤器清除不需要的内容。

  • 尽可能用匿名函数提升代码可读性与模块化程度。

  • 如需保留键名与原数组一致,可配合 ARRAY_FILTER_USE_BOTH 使用。