Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_find

Returns the first element for which the function returned true.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$callbackcallableThe test function: receives the value and the key.

Return value

mixedThe matching element, or `null`.

Examples

The first matching element:

<?php
 
$users = [['name' => 'Anna', 'age' => 17], ['name' => 'Oleg', 'age' => 31]];
 
echo array_find($users, fn ($user) => $user['age'] >= 18)['name'];

Output:

Oleg

The companion functions array_any() and array_all():

<?php
 
$numbers = [3, -1, 5];
 
var_dump(array_any($numbers, fn ($n) => $n < 0));
var_dump(array_all($numbers, fn ($n) => $n > 0));

Output:

bool(true)
bool(false)

Notes

The functions appeared in PHP 8.4. In older versions the first element is found with array_filter() and reset(), or with a loop.

See also

  • array_filter — Keeps the array elements that pass a test.
  • array_search — Searches an array for a value and returns its key.
  • in_array — Checks whether a value exists in an array.

Related recipes

In the tutorial

  • Array functions — Processing arrays in PHP without loops — array_map, array_filter, array_reduce, searching and slicing.

Thanks for reading!

Donate to the site — we work hard for you.