iter icon indicating copy to clipboard operation
iter copied to clipboard

Feature req: something with semantics `array_usearch()` would have if it existed

Open rulatir opened this issue 2 years ago • 3 comments
trafficstars

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.

rulatir avatar Nov 28 '22 21:11 rulatir

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).

nikic avatar Dec 04 '22 20:12 nikic

Brainstorming:

  • Optional boolean argument to search().
  • first() and firstKey(), returning respectively the first value/key from the iterable, else null; easily enough combined with filter(). Maybe firstKey() should be mean and throw if iterable is empty, because unfortunately iterators can yield null as keys, so you couldn't tell between "empty" and "the first key is null" otherwise.

rulatir avatar Dec 05 '22 21:12 rulatir

BTW, both firstValue and firstKey should throw, for consistency. Returning null would be indistinguishable from valid key/value in both cases.

dakujem avatar Feb 21 '24 12:02 dakujem