On Thu, Jun 1, 2023, at 4:02 PM, Janusz Szczypka wrote:
> 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
As with the array_group thread:
What is the argument to put these functions in hard to update C, rather than
PHP that is easy to download with Composer? "could be a nice addition" is not
a compelling argument. Is it substantially faster? It is truly universally
used? Does it correct some security concern?
Those are the questions that stdlib additions need to answer.
--Larry Garfield
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php