Finding elements with array_find, array_any and array_all

suggest change

PHP 8.4 added four functions that search an array with a callback:

Function Returns Not found / empty array
array_find($array, $callback) value of the first element for which the callback returns true null
array_find_key($array, $callback) key of that element null
array_any($array, $callback) true if the callback returns true for at least one element false
array_all($array, $callback) true if the callback returns true for every element true

PHP 8.5 added array_first() and array_last(), which return the first and last value of an array without touching its internal pointer. PHP 8.1 added array_is_list(), which checks if the keys are 0, 1, 2, ... in order.

This article covers all of them: how they stop early, what the callback receives, the null trap, and which older idioms they replace. All examples were run with PHP 8.5. In error messages, paths are shortened to /app/.

To keep all matching elements instead of the first one, use array_filter() (see Filtering an array). To check for an exact value, in_array() and array_search() are still the right tools (see Checking if a value exists in array).

A first look

<?php
$users = [
    ['id' => 1, 'name' => 'Ann',   'role' => 'admin',  'active' => true],
    ['id' => 2, 'name' => 'Bob',   'role' => 'editor', 'active' => false],
    ['id' => 3, 'name' => 'Cleo',  'role' => 'editor', 'active' => true],
];

$editor = array_find($users, fn($u) => $u['role'] === 'editor');
echo $editor['name'], "\n";

$key = array_find_key($users, fn($u) => $u['role'] === 'editor');
var_dump($key);

var_dump(array_any($users, fn($u) => !$u['active']));
var_dump(array_all($users, fn($u) => $u['id'] > 0));

Output:

Bob
int(1)
bool(true)
bool(true)

Note that the array comes first and the callback second. That is the same order as array_filter() and the opposite of array_map().

What they replace

Before PHP 8.4, finding the first match took either array_filter() plus reset(), or a foreach loop with break:

<?php
$users = [
    ['name' => 'Ann', 'role' => 'admin'],
    ['name' => 'Bob', 'role' => 'editor'],
    ['name' => 'Cleo', 'role' => 'editor'],
];

// before PHP 8.4: array_filter() visits every element, then you take the first
$editors = array_filter($users, fn($u) => $u['role'] === 'editor');
$first = $editors ? reset($editors) : null;
echo $first['name'], "\n";

// or a loop with break
$first = null;
foreach ($users as $u) {
    if ($u['role'] === 'editor') {
        $first = $u;
        break;
    }
}
echo $first['name'], "\n";

// PHP 8.4
echo array_find($users, fn($u) => $u['role'] === 'editor')['name'], "\n";

Output:

Bob
Bob
Bob

The array_filter() version builds a temporary array of all matches and calls the callback for every element, even though only the first match is needed. The loop is efficient but takes seven lines. array_find() is one expression and stops at the first match.

Likewise, count(array_filter(...)) > 0 becomes array_any(...), and count(array_filter(...)) === count($array) becomes array_all(...).

They stop early

All four functions stop calling the callback as soon as they know the answer:

<?php
$numbers = [3, 8, 5, 12, 7];

$calls = 0;
$isBig = function (int $n) use (&$calls): bool {
    $calls++;
    echo "checking $n\n";
    return $n > 6;
};

$found = array_find($numbers, $isBig);
echo "found $found after $calls calls\n\n";

$calls = 0;
$all = array_all($numbers, $isBig);
var_dump($all);
echo "$calls calls\n";

Output:

checking 3
checking 8
found 8 after 2 calls

checking 3
bool(false)
1 calls

This matters when the callback is expensive (a regex, a database lookup, a file check) or the array is large. Don't rely on the callback running for every element. If you need side effects for every element, use foreach or array_walk().

The callback gets the value and the key

The callback is called as $callback($value, $key). Most callbacks only need the value, but the key is there when you need it:

<?php
$prices = ['apple' => 1.20, 'mango' => 2.50, 'kiwi' => 0.80];

// the callback gets the value first, then the key
$item = array_find_key($prices, fn(float $price, string $name) => strlen($name) === 4 && $price < 1);
var_dump($item);

$cheapM = array_find($prices, fn($price, $name) => str_starts_with($name, 'm'));
var_dump($cheapM);

var_dump(array_all($prices, fn($price, $name) => ctype_lower($name)));

Output:

string(4) "kiwi"
float(2.5)
bool(true)

This is different from array_filter(), which passes only the value unless you add the ARRAY_FILTER_USE_KEY or ARRAY_FILTER_USE_BOTH flag.

With a list, the key is the index. That lets a callback look at the neighbouring element, for example to check if a list is sorted:

<?php
function isSorted(array $list): bool
{
    return array_all($list, fn($v, $i) => $i === 0 || $list[$i - 1] <= $v);
}

var_dump(isSorted([1, 2, 2, 5]));
var_dump(isSorted([1, 3, 2]));

Output:

bool(true)
bool(false)

The return value of the callback is converted to bool with the usual truthiness rules, so returning 0, '', '0' or [] counts as false. Return a real bool to avoid surprises.

Built-in functions as callbacks

Because the key is always passed as a second argument, a built-in function that takes exactly one argument fails when you pass it with the first-class callable syntax:

<?php
$codes = ['10', '42', '7'];

try {
    var_dump(array_all($codes, ctype_digit(...)));
} catch (ArgumentCountError $e) {
    echo get_class($e), ': ', $e->getMessage(), "\n";
}

// wrap it so only the value is passed
var_dump(array_all($codes, fn($v) => ctype_digit($v)));

// user-defined functions ignore extra arguments, so they are fine
function isEven(int $n): bool { return $n % 2 === 0; }
var_dump(array_any([1, 3, 4], isEven(...)));

Output:

ArgumentCountError: ctype_digit() expects exactly 1 argument, 2 given
bool(true)
bool(true)

Internal functions check the argument count strictly; user-defined functions and closures silently ignore extra arguments. So is_string(...), ctype_digit(...), is_numeric(...) and similar functions must be wrapped in an arrow function.

Worse, a built-in function with a second parameter will happily take the key as that argument. Here str_contains($value, $key) is called, and 'box' contains its key 'x':

<?php
// str_contains($haystack, $needle) silently gets the key as $needle
var_dump(array_find(['x' => 'box', 'y' => 'yes'], str_contains(...)));

Output:

string(3) "box"

When in doubt, write fn($v) => ....

The null trap

array_find() returns null when nothing matches. If the array can contain null, you can't tell "found a null" from "not found":

<?php
$settings = ['debug' => null, 'cache' => false, 'level' => 0];

// array_find returns null both for "not found" and for a found null value
var_dump(array_find($settings, fn($v) => $v === null));
var_dump(array_find($settings, fn($v) => $v === 'missing'));

// array_find_key tells them apart: a key is never null
$key = array_find_key($settings, fn($v) => $v === null);
if ($key === null) {
    echo "not found\n";
} else {
    echo "found at '$key': ", var_export($settings[$key], true), "\n";
}

Output:

NULL
NULL
found at 'debug': NULL

Array keys are always int or string, never null, so array_find_key() gives an unambiguous answer. Use it whenever null is a possible value.

The second half of the trap is checking the result with a truthiness test. 0, '', '0', false and [] are valid matches but falsy:

<?php
$scores = [0, 0, 5];

// wrong: 0 is a valid result but falsy
$firstEven = array_find($scores, fn($n) => $n % 2 === 0);
if (!$firstEven) {
    echo "no even score?\n";
}

// right: compare with null
if ($firstEven !== null) {
    echo "first even score: $firstEven\n";
}

// a default with ??
$name = array_find(['ann', 'bob'], fn($n) => strlen($n) > 5) ?? 'nobody';
echo $name, "\n";

// array_find_key returns int 0 for the first element
$pos = array_find_key(['a', 'b'], fn($v) => $v === 'a');
var_dump($pos);

Output:

no even score?
first even score: 0
nobody
int(0)

Always compare with !== null, or use ?? to supply a default. The same goes for array_find_key(), which returns 0 for a match on the first element of a list.

Note the difference from array_search(), which returns false when nothing is found:

<?php
$a = [1, 2, 3];
// array_search() finds a key by value, array_find_key() by condition
var_dump(array_search(2, $a, true));
var_dump(array_find_key($a, fn($v) => $v >= 2));
// not found: array_search returns false, array_find_key returns null
var_dump(array_search(9, $a, true));
var_dump(array_find_key($a, fn($v) => $v > 9));

Output:

int(1)
int(1)
bool(false)
NULL

Empty arrays

<?php
var_dump(array_find([], fn($v) => true));
var_dump(array_find_key([], fn($v) => true));
var_dump(array_any([], fn($v) => true));
var_dump(array_all([], fn($v) => false));

Output:

NULL
NULL
bool(false)
bool(true)

array_all() returns true for an empty array, whatever the callback does: no element breaks the rule. This is standard logic ("vacuous truth") and the same as every() in JavaScript or all() in Python, but it can surprise you in validation code. If an empty input should fail, check for it separately: $items !== [] && array_all($items, ...).

Arrays only, not iterables

The functions take an array, not an iterable. Generators and other Traversable objects are rejected:

<?php
function numbers(): Generator { yield 1; yield 2; yield 3; }

try {
    array_find(numbers(), fn($n) => $n > 1);
} catch (TypeError $e) {
    echo $e->getMessage(), "\n";
}

var_dump(array_find(iterator_to_array(numbers()), fn($n) => $n > 1));

Output:

array_find(): Argument #1 ($array) must be of type array, Generator given
int(2)

iterator_to_array() works, but it reads the whole generator first, so you lose the early stop. For a large or infinite generator, use a foreach loop with break. See Generators.

Practical examples

Objects

The functions work on arrays of objects just as well. Typing the callback parameter documents what the array holds:

<?php
final class Product
{
    public function __construct(
        public readonly string $sku,
        public readonly int $stock,
        public readonly float $price,
    ) {}
}

$cart = [
    new Product('A-100', stock: 3, price: 9.99),
    new Product('B-200', stock: 0, price: 24.50),
    new Product('C-300', stock: 12, price: 4.25),
];

$outOfStock = array_find($cart, fn(Product $p) => $p->stock === 0);
if ($outOfStock !== null) {
    echo "Sorry, {$outOfStock->sku} is out of stock\n";
}

if (array_all($cart, fn(Product $p) => $p->price < 50)) {
    echo "Every item qualifies for the under-50 promo\n";
}

$index = array_find_key($cart, fn(Product $p) => $p->sku === 'C-300');
echo "C-300 is at index $index\n";

Output:

Sorry, B-200 is out of stock
Every item qualifies for the under-50 promo
C-300 is at index 2

Validation and permissions

<?php
$input = ['name' => 'Ann', 'email' => 'ann@example.com', 'age' => ''];
$required = ['name', 'email', 'age'];

$missing = array_find($required, fn($field) => trim($input[$field] ?? '') === '');
if ($missing !== null) {
    echo "Field '$missing' is required\n";
}

$userRoles = ['viewer', 'editor'];
$canEdit = array_any($userRoles, fn($r) => in_array($r, ['admin', 'editor'], true));
var_dump($canEdit);

// in_array() is enough for an exact value; array_any() is for a condition
var_dump(in_array('editor', $userRoles, true));
var_dump(array_any($userRoles, fn($r) => str_ends_with($r, 'or')));

Output:

Field 'age' is required
bool(true)
bool(true)
bool(true)

Matching keys: a tiny router

When the interesting information is in the keys, use the second callback parameter and array_find_key():

<?php
$routes = [
    '#^/$#'             => 'home',
    '#^/posts/(\d+)$#'  => 'showPost',
    '#^/posts$#'        => 'listPosts',
];

function route(array $routes, string $path): string
{
    $pattern = array_find_key($routes, fn($handler, $regex) => preg_match($regex, $path) === 1);
    return $pattern === null ? 'notFound' : $routes[$pattern];
}

foreach (['/', '/posts/42', '/posts', '/about'] as $path) {
    printf("%-10s => %s\n", $path, route($routes, $path));
}

Output:

/          => home
/posts/42  => showPost
/posts     => listPosts
/about     => notFound

Order matters: the first matching pattern wins and the rest are never tried.

array_first and array_last (PHP 8.5)

array_first() and array_last() return the first and last value of an array, whatever its keys are. They return null for an empty array. They are the value counterparts of array_key_first() and array_key_last() (PHP 7.3):

<?php
$queue = [10 => 'first', 20 => 'second', 30 => 'third'];

var_dump(array_first($queue));
var_dump(array_last($queue));
var_dump(array_key_first($queue));
var_dump(array_key_last($queue));

var_dump(array_first([]));
var_dump(array_last([]));

Output:

string(5) "first"
string(5) "third"
int(10)
int(30)
NULL
NULL

Replacing reset(), end() and array_key_first()

Before PHP 8.5 the usual idioms were reset($a), end($a), $a[array_key_first($a)] and $a[array_key_last($a)]. Each has a problem:

reset() and end() move the internal array pointer. This can break code that iterates with current()/next() (see Using internal array pointers). array_first() and array_last() leave it alone:

<?php
$items = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
next($items);
echo "pointer at: ", current($items), "\n";

// old idioms: reset() and end() move the internal pointer
$first = reset($items);
$last = end($items);
echo "$first $last, pointer at: ", current($items), "\n";

// PHP 8.5: the pointer is not touched
reset($items);
next($items);
echo array_first($items), ' ', array_last($items), ", pointer at: ", current($items), "\n";

Output:

pointer at: banana
apple cherry, pointer at: cherry
apple cherry, pointer at: banana

reset() and end() take the array by reference, so they need a variable. Passing a function result raises a notice:

<?php
function loadTags(): array { return ['php', 'arrays', 'tips']; }

echo array_first(loadTags()), "\n";
echo array_last(loadTags()), "\n";

// reset() and end() take the array by reference
echo end(loadTags()), "\n";

Output:

php
tips

Notice: Only variables should be passed by reference in /app/11.php on line 8
tips

reset() and end() return false for an empty array, which can't be told apart from a false element. array_first() returns null instead, which is easier to use with ?? (but has the same ambiguity for arrays that contain null; check $a === [] first if that matters):

<?php
$empty = [];
var_dump(reset($empty), end($empty));
var_dump(array_first($empty), array_last($empty));

// false is ambiguous with reset()
$flags = [false, true];
var_dump(reset($flags));

Output:

bool(false)
bool(false)
NULL
NULL
bool(false)

$a[array_key_first($a)] works, but it is long, and on an empty array array_key_first() returns null, so $a[null] raises an "Undefined array key" warning (plus, in PHP 8.5, a deprecation for using null as an array offset).

In PHP 8.5 code, use array_first($a) and array_last($a). Use reset()/end() only when you actually want to move the pointer.

array_is_list (PHP 8.1)

array_is_list() returns true if the array's keys are exactly 0, 1, 2, ..., count - 1, in that order. An empty array is a list:

<?php
var_dump(array_is_list([]));
var_dump(array_is_list(['a', 'b', 'c']));
var_dump(array_is_list([0 => 'a', 1 => 'b']));
var_dump(array_is_list([1 => 'a', 2 => 'b']));   // doesn't start at 0
var_dump(array_is_list([1 => 'b', 0 => 'a']));   // keys out of order
var_dump(array_is_list(['x' => 1]));

$filtered = array_filter([1, 2, 3, 4], fn($n) => $n % 2 === 0);
var_dump(array_is_list($filtered));               // keys 1 and 3
var_dump(array_is_list(array_values($filtered)));

Output:

bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
bool(false)
bool(false)
bool(true)

PHP has one array type for both lists and maps, and many functions (array_filter(), unset(), array_unique()) leave gaps in the keys. The difference shows up when you encode JSON: a list becomes a JSON array, anything else becomes an object. array_is_list() is how you check for that before it reaches a client:

<?php
$filtered = array_filter([1, 2, 3, 4], fn($n) => $n % 2 === 0);
echo json_encode($filtered), "\n";
echo json_encode(array_values($filtered)), "\n";

function toJsonList(array $items): string
{
    if (!array_is_list($items)) {
        throw new InvalidArgumentException('expected a list, got keys: ' . implode(', ', array_keys($items)));
    }
    return json_encode($items);
}

echo toJsonList(['a', 'b']), "\n";
try {
    echo toJsonList($filtered), "\n";
} catch (InvalidArgumentException $e) {
    echo $e->getMessage(), "\n";
}

Output:

{"1":2,"3":4}
[2,4]
["a","b"]
expected a list, got keys: 1, 3

It is also useful in assertions and for documenting list<T> parameters that static analysers like PHPStan and Psalm understand. To turn any array into a list, call array_values().

Older PHP versions

On PHP 8.3 and earlier, the symfony/polyfill-php84 and symfony/polyfill-php85 packages provide these functions. They are also short enough to write yourself:

<?php
function my_array_find(array $array, callable $callback): mixed
{
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return $value;
        }
    }
    return null;
}

function my_array_any(array $array, callable $callback): bool
{
    foreach ($array as $key => $value) {
        if ($callback($value, $key)) {
            return true;
        }
    }
    return false;
}

function my_array_all(array $array, callable $callback): bool
{
    foreach ($array as $key => $value) {
        if (!$callback($value, $key)) {
            return false;
        }
    }
    return true;
}

Use different names, or wrap the definitions in if (!function_exists('array_find')), so they don't clash with the built-in functions on PHP 8.4+.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents