ZetCode

PHP array_find 函数

最后修改于 2025 年 3 月 13 日

PHP 的 array_find 函数使用回调函数在数组中搜索元素。它返回第一个匹配的元素或 null。

基本定义

array_find 函数在数组中搜索第一个满足条件的元素。它对查找特定的数组项很有用。

语法:array_find(array $array, callable $callback): mixed。回调函数应该对匹配的元素返回 true。如果未找到匹配项,则返回 null。

基本 array_find 示例

此示例演示了在数组中查找第一个偶数。

basic_array_find.php
<?php

declare(strict_types=1);

function array_find(array $array, callable $callback): mixed {
    foreach ($array as $element) {
        if ($callback($element)) {
            return $element;
        }
    }
    return null;
}

$numbers = [1, 3, 4, 7, 8];
$firstEven = array_find($numbers, fn($n): bool => $n % 2 === 0);

echo $firstEven ?? 'Not found'; 

该代码在数组中找到第一个偶数 (4)。回调函数检查每个元素,直到找到匹配项,然后立即返回它。

通过属性查找对象

在数组中搜索一个对象,其中特定属性满足条件。

object_property_find.php
<?php

declare(strict_types=1);

class User {
    public function __construct(
        public string $name,
        public int $age
    ) {}
}

$users = [
    new User("Alice", 25),
    new User("Bob", 30),
    new User("Charlie", 22)
];

$youngUser = array_find($users, fn(User $u): bool => $u->age < 25);

echo $youngUser?->name ?? 'Not found'; 

这找到了第一个年龄小于 25 岁的用户。回调函数检查 age 属性,返回匹配的 User 对象(在本例中为 Charlie)。

通过模式查找字符串

使用 array_find 定位第一个匹配正则表达式模式的字符串。

string_pattern_find.php
<?php

declare(strict_types=1);

$words = ["apple", "banana", "cherry", "date"];
$fruitWithA = array_find($words, fn(string $w): bool => preg_match('/a/', $w));

echo $fruitWithA ?? 'Not found'; 

这找到了第一个包含字母 'a' 的水果名称。回调函数使用 preg_match 测试每个字符串,直到找到匹配项(apple)。

在关联数组中查找

根据键值组合搜索关联数组中的项目。

associative_array_find.php
<?php

declare(strict_types=1);

$products = [
    ['id' => 1, 'name' => 'Laptop', 'stock' => 5],
    ['id' => 2, 'name' => 'Phone', 'stock' => 0],
    ['id' => 3, 'name' => 'Tablet', 'stock' => 10]
];

$outOfStock = array_find($products, fn(array $p): bool => $p['stock'] === 0);

echo $outOfStock['name'] ?? 'All in stock'; 

这找到了第一个库存为零的产品。回调函数检查每个关联数组中的 'stock' 键,返回匹配的项目(Phone)。

使用复杂条件查找

在回调函数中组合多个条件以进行更复杂的搜索。

complex_condition_find.php
<?php

declare(strict_types=1);

$employees = [
    ['name' => 'John', 'department' => 'IT', 'salary' => 75000],
    ['name' => 'Jane', 'department' => 'HR', 'salary' => 65000],
    ['name' => 'Bob', 'department' => 'IT', 'salary' => 80000]
];

$highEarnerInIT = array_find($employees, fn(array $e): bool => 
    $e['department'] === 'IT' && $e['salary'] > 70000
);

echo $highEarnerInIT['name'] ?? 'Not found'; 

这找到了第一个 IT 部门的员工,收入超过 70,000。回调函数结合了两个条件来精确定位所需的元素(John)。

最佳实践

来源

PHP Array Filter 文档(相关功能)

本教程介绍了 PHP array_find 模式,并提供了实用示例,展示了它在各种数组搜索场景中的用法。

作者

我的名字是 Jan Bodnar,我是一位充满激情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。我拥有超过十年的编程教学经验。

列出 所有 PHP 数组函数