iter
iter copied to clipboard
Feature req: something with semantics `array_usearch()` would have if it existed
One super common use case is finding the index at which you need to insert something into an array.
Built-in array_search() does this if you are looking for an element by exact value or identity. What is dearly missing is a function that returns the key of the first element that matches a user-defined predicate. While it is trivial to write a simple loop, the frequency with which this is needed (particularly when writing complex refactorings using nikic/php-parser) adds up to some cognitive load. It would be great to have a function that DoesJustThat™, and as part of a widely used library too, rather than as a copypaste in every project's myfuncs.php.
Generally sounds like a reasonable addition, but I'm not sure what a good name would be. We already have a search() function which returns the value matching a predicate. searchKey() would be a possibility, but I'm a bit worried that this would carry the incorrect implication that the predicate also works on the keys (rather than values).
Brainstorming:
- Optional boolean argument to
search(). first()andfirstKey(), returning respectively the first value/key from the iterable, else null; easily enough combined withfilter(). MaybefirstKey()should be mean and throw if iterable is empty, because unfortunately iterators can yieldnullas keys, so you couldn't tell between "empty" and "the first key isnull" otherwise.
BTW, both firstValue and firstKey should throw, for consistency. Returning null would be indistinguishable from valid key/value in both cases.