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

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

Advertisement

Answer

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

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