Proposal: addition of array_find() and array_find_key() functions

From: Date: Thu, 01 Jun 2023 16:02:18 +0000
Subject: Proposal: addition of array_find() and array_find_key() functions
Groups: php.internals 
Request: Send a blank email to internals+get-120500@lists.php.net to get a copy of this message
Dear PHP Internals, I would like to propose new functions to search in arrays: array_find() and array_find_key(). array_find(): This function would allow developers to find the first element in an array that satisfies a specific condition. The condition would be defined by a callback function. The functionality would be similar to the existing array_filter() function but would instead return the first element that matches the callback condition, rather than all matching elements. This function can be used in a way simliar to in_array with added functionality of custom check. array_find_key(): This function would return the key of the first element in an array that matches a given condition, defined by a callback function. This function can be used in a way simliar to array_search with added functionality of custom check. Both functions stop processing after first match is found, so any side effects of the callbacks should be avoided. Here are the proposed function definitions: /**  * @param callable(mixed):bool $callback  */ function array_find(callable $callback, array $array) {
    foreach ($array as $row) {
        if (call_user_func($callback, $row) === true) {
            return $row;
        }
    }
    return null;
} /**  * @param callable(mixed):bool $callback  * @return null|int|string  */ function array_find_key(callable $callback, array $array) {
    foreach($array as $key => $row) {
        if (call_user_func($callback, $row) === true) {
            return $key;
        }
    }
    return null;
} Both functions are easy to implement in PHP (and probably as easy to implement in C), but IMHO could be nice addition to set of array related functions in PHP. If the response to this e-mail will be positive, I will prepare RFC. We should also discuss order of arguments as the functions are similar to both array_search/in_array with condition-array and array_filter with array-condition, but as you can see above I am leaning towards condition-array. Looking forward to hearing your thoughts. Best regards, Janusz

« previous php.internals (#120500) next »