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

  • PHP 8.4+ includes array_find() which will do exactly what you want. If you cannot install PHP 8.4+, you can use the Symfony polyfill of 8.4 which includes array_find().