PHP 8 reference · Array Functions

PHP array_find() Function

Return the first element for which a callback returns true, or null if none match. Added in PHP 8.4.

PHP 8 Since 8.4

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_find(array $array, callable $callback): mixed

Parameters

ParameterDescription
array The input array.
callback fn($value, $key) returns true for a match.

Return value

The first matching value, or null.

Examples

Find a record
<?php
$users = [["name" => "Ada", "admin" => false], ["name" => "Alan", "admin" => true]];
$admin = array_find($users, fn($u) => $u["admin"]);
echo $admin["name"], "\n";

Output

Alan

Run this on your computer — see “Get Started” for setup.

No match, and using the key
<?php
var_dump(array_find([1, 3, 5], fn($n) => $n % 2 === 0));
echo array_find(["a" => 1, "b" => 20], fn($v, $k) => $k === "b"), "\n";

Output

NULL
20

Run this on your computer — see “Get Started” for setup.

Before PHP 8.4, write a foreach loop that returns on the first match, or use array_values(array_filter($a, $fn))[0] ?? null (which checks every element).

Version history

VersionChange
PHP 8.4Added

In other languages

Was this page helpful?