Add Arr::find()

This commit is contained in:
Giuseppe Criscione 2024-10-25 00:34:25 +02:00
parent 4d9737d2e3
commit 8d2325bc67

View File

@ -399,6 +399,27 @@ class Arr
return false; return false;
} }
/**
* Find the first element of an array passing a test callback
*
* The key of each element is passed to the callback as second argument
*
* @template T of mixed
*
* @param array<T> $array
*
* @return ?T
*/
public static function find(array $array, callable $callback): mixed
{
foreach ($array as $key => $value) {
if ($callback($value, $key)) {
return $value;
}
}
return null;
}
/** /**
* Get the value corresponding to the specified key from each element of an array * Get the value corresponding to the specified key from each element of an array
* *