Search

Laravel 5 Collections: Finding an Element Key Conditionally With search

April 22, 2018 —John Koster

The search method is used to search the collection for a given $value. If the given $value is found, the value's corresponding key is returned. If the $value is not found in the collection, the search method will return false. The search method also defines the parameter $strict which will cause the search method to check the data types of the items in the collection with the provided $value to ensure they match.

#Signature

1public function search(
2 $value,
3 $strict = false
4);

#Example Use

An argument passed for $value can either be a value, such as 4 or a callback function that accepts both an $item and $key parameter. The following code examples will demonstrate both uses of the search method. The returned value of each method call will appear above the method call as a comment.

1use Illuminate\Support\Collection;
2 
3// Create a new collection instance.
4$collection = new Collection([
5 'first', 'second', 'third', 4
6]);
7 
8// 3
9$key = $collection->search('4');
10 
11// 0
12$key = $collection->search('first');
13 
14// false
15$key = $collection->search('fourth');

The following code example will demonstrate the affect of the $strict parameter:

1// false
2$key = $collection->search('4', true);
3 
4// 3
5$key = $collection->search(4, true);

We can also supply a custom comparison function when performing the search; our custom function should return either true or false, depending on whether or not the value matches our search query:

1$result = $collection->search(function ($value, $key) {
2 return $value === 4;
3});

After the above code has executed, the $result variable would contain the value 3 since it matches the conditions within our custom comparison function.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.