Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...)
| From: | tyson andre | Date: | Sat, 29 Aug 2020 23:48:43 +0000 |
| Subject: | Re: Proposal: Adding functions any(iterable $input, ?callable $cb = null, int $use_flags=0) and all(...) | ||
| References: | 1 2 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-111715@lists.php.net to get a copy of this message | ||
> The “any” check is just to if anything in the iterable passes the predicate, yeah??
>
> What I find myself doing more often is wanting the first thing to satisfy the predicate - a
> “first” function, if you will.
There's multiple things such a function could return - The key of the entry (could be
false/null), the value of the entry (could be false/null), or a combination of the key and value
(rarely what we want).
I'm not aware of any exact matches for that - array_filter processes all values, and
array_search doesn't accept a callback.
array_search_callback() could be added, but I don't plan to expand the scope of
this RFC and there are multiple ways to do that.
> This could skip the step of iterating to find of something satisfies the predicate. Then
> iterating again to get one or more items that do satisfy it..
>
> Trying to think of a use case where I would want to check, but not do anything with that
> knowledge.
Anywhere where you'd want to check for membership in a short-circuiting way, similar to
situations where || or && would be called,
but with a variable number of callbacks or repeating the same operation multiple times.
It also reduces the indentation and line count needed
```
$this->assertTrue(all($valueList, fn($v) => $v->isValid()));
all($startupCallbacks, 'call_user_func') || exit("startup failed");
if (any($fieldList, fn($field) => in_array($field->name, ['fooEnabled',
'fooEnabled2']))) {
doFoo();
}
```
- Tyson