Search code examples
phpcollectionsfunctional-programming

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

// would return the element or null
check_in_array($myArray, function($element) { return $elemnt->foo() > 10; });

But I don't know of any PHP function which does this. One "approximation" I came up with:

$check = array_filter($myArray, function($element) { ... });
if ($check) 
    //...

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)


Solution

  • You can write your own function ;)

    function callback_search ($array, $callback) { // name may vary
        return array_filter($array, $callback);
    }
    

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