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
Syntax
array_find(array $array, callable $callback): mixed
Parameters
| Parameter | Description |
|---|---|
array |
The input array. |
callback |
fn($value, $key) returns true for a match. |
Return value
The first matching value, or null.
Examples
<?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.
<?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
| Version | Change |
|---|---|
| PHP 8.4 | Added |
In other languages
array.find()· JavaScript
Related
array_find_key()· Return the key of the first element for which a callback returns true, or null if none match. Added in PHP 8.4.array_filter()· Keep only the elements for which a callback returns true. Without a callback it removes empty values; keys are kept.array_any()· Return true if at least one element passes a callback test, stopping at the first match. Added in PHP 8.4.array_search()· Search an array for a value and return the first matching key, or false if it isn't there.- PHP Array Functions · tutorial
- PHP Arrays · tutorial