Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_find_key

Returns the key of the first element that satisfies a condition.

Syntax

array_find_key(array $array, callable $callback): int|string|null

Parameters

ParameterTypeDescription
$arrayarrayThe input array.
$callbackcallableA test function: receives the value and the key.

Return value

int|string|nullThe key, or `null` if nothing is found.

Examples

Who first scored above 90:

<?php
 
$scores = ['Anna' => 72, 'Oleg' => 95, 'Ivan' => 98];
 
echo array_find_key($scores, fn ($score) => $score > 90);

Output:

Oleg

Notes

The function appeared in PHP 8.4. array_search() looks for an exact value, while this one searches by a condition.

See also

  • array_find — Returns the first element for which the function returned true.
  • array_search — Searches an array for a value and returns its key.
  • array_key_first — Returns the first key of an array.

In the tutorial

  • New in PHP 8.4 — PHP 8.4 features — property hooks, asymmetric visibility, calling a method right after new, and new array functions.

Thanks for reading!

Donate to the site — we work hard for you.