From 8d2325bc6744d7b6eef417e85263025de95f8bed Mon Sep 17 00:00:00 2001 From: Giuseppe Criscione <18699708+giuscris@users.noreply.github.com> Date: Fri, 25 Oct 2024 00:34:25 +0200 Subject: [PATCH] Add `Arr::find()` --- formwork/src/Utils/Arr.php | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/formwork/src/Utils/Arr.php b/formwork/src/Utils/Arr.php index bc3bf36a..78edaf07 100644 --- a/formwork/src/Utils/Arr.php +++ b/formwork/src/Utils/Arr.php @@ -399,6 +399,27 @@ public static function some(array $array, callable $callback): bool 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 $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 *