array_find_key()

array_find_key() — Returns the key of the first element satisfying a callback function.

Built-in function of PHP 8.5. The manual lists it as available in PHP 8 >= 8.4.0. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

array_find_key() returns the key of the first element of an array for which the given callback returns true. If no matching element is found the function returns null.

Signature

array_find_key(array $array, callable $callback): mixed callback(mixed $value, mixed $key): bool

Parameters

ParameterTypeWhat it takes
$arrayarrayThe array that should be searched.
$callbackcallableThe callback function to call to check each element, which must be of the following signature: function callback(mixed $value, mixed $key): bool If this function returns true, the key is returned from array_find_key() and the callback will not be called for further elements.

Return value

The function returns the key of the first element for which the callback returns true. If no matching element is found the function returns null.

Example

A runnable snippet:

$array = [ 'a' => 'dog', 'b' => 'cat', 'c' => 'cow', 'd' => 'duck', 'e' => 'goose', 'f' => 'elephant' ]; // Find the first animal with a name longer than 4 characters. var_dump(array_find_key($array, function (string $value) { return strlen($value) > 4; })); // Find the first animal whose name begins with f. var_dump(array_find_key($array, function (string $value) { return str_starts_with($value, 'f'); })); // Find the first animal where the array key is the first symbol of the animal. var_dump(array_find_key($array, function (string $value, $key) { return $value[0] === $key; })); // Find the first animal where the array key matching a RegEx. var_dump(array_find_key($array, function ($value, $key) { return preg_match('/^([a-f])$/', $key); }));

Output:

string(1) "e" NULL string(1) "c" string(1) "a"

See also

array_find(), array_all(), array_any(), array_filter(), array_reduce()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page array_find_key() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.