Skip to content
Advertisement

Elegant way to search an PHP array using a user-defined function

Basically, I want to be able to get the functionality of C++’s find_if(), Smalltalk’s detect: etc.:

JavaScript

But I don’t know of any PHP function which does this. One “approximation” I came up with:

JavaScript

The downside of this is that the code’s purpose is not immediately clear. Also, it won’t stop iterating over the array even if the element was found, although this is more of a nitpick (if the data set is large enough to cause problems, linear search won’t be an answer anyway)

Advertisement

Answer

You can write your own function 😉

JavaScript

This maybe seems useless, but it increases semantics and can increase readability

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement