Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
rulatir opened this issue Nov 28, 2022 · 3 comments

Comments

@rulatir
Copy link

rulatir commented Nov 28, 2022

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.

@nikic
Copy link
Owner

nikic commented Dec 4, 2022

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

@rulatir
Copy link
Author

rulatir commented Dec 5, 2022

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.

@dakujem
Copy link

dakujem commented Feb 21, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants