Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 813
lethal-guitar Avatar asked Jan 08 '13 22:01

lethal-guitar


People also ask

How can we search an element from an array using built in function in PHP?

The array_search() is an inbuilt function in PHP that is used to search for a particular value in an array, and if the value is found then it returns its corresponding key. If there are more than one values then the key of the first matching value will be returned.

Which of the following is a PHP function for searching arrays?

The array_search() function search an array for a value and returns the key.

How do you search a multidimensional array?

Multidimensional array search using array_search() method: The array_search() is an inbuilt function which searches for a given value related to the given array column/key. This function only returns the key index instead of a search path.

How do you search an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.


1 Answers

To pull the first one from the array, or return false:

current(array_filter($myArray, function($element) { ... })) 

More info on current() here.

like image 110
Izkata Avatar answered Oct 06 '22 09:10

Izkata