Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_find(), array_any() and array_all() functions

Reference for PHP 8.4 array_find(), array_find_key(), array_any() and array_all(): search an array with a callback and test conditions on its elements.

PHP 8.4 added four small functions that take a callback and answer common questions about an array. array_find() returns the first value for which the callback returns true, and array_find_key() returns its key. array_any() says whether at least one element passes, and array_all() says whether every element passes.

They stop as soon as the answer is known, so they are faster than array_filter() when you only need one result. They exist in PHP 8.4 and later only.

PHP
<?php
$found = array_find([3, 8, 12], fn($n) => $n > 5);   // 8

Try it

PHP Finding the first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Testing all and any

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_find(array $array, callable $callback): mixed
array_find_key(array $array, callable $callback): mixed
array_any(array $array, callable $callback): bool
array_all(array $array, callable $callback): bool
Name Description
$array The array to search.
$callback Called as callback($value, $key). Its return value is treated as true or false.

Return value: array_find() returns the first matching value or null; array_find_key() returns the first matching key or null; array_any() and array_all() return bool.

Usage notes

  • Order: elements are checked in array order, and checking stops at the first decisive element.
  • null is ambiguous. A null from array_find() could mean "no match" or "the match is the value null". Use array_find_key() or array_any() if that matters.
  • Empty arrays: array_any() returns false, and array_all() returns true (nothing fails).
  • Not like array_filter(): there the callback gets only the value unless you ask for the key with a mode flag. Here it always gets ($value, $key).
  • Before PHP 8.4, use a foreach with return, or array_filter() and reset().
  • Compared with in_array() and array_search(), these accept any condition, not just equality.