November 30, 2016 —John Koster
search($value, $strict = false)
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 make sure they match.
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.
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first', 'second', 'third', 4 8]); 9 10// 311$key = $collection->search('4');12 13// 014$key = $collection->search('first');15 16// false17$key = $collection->search('fourth');
The following code example will demonstrate the affect of the $strict
parameter:
1<?php2 3// false4$key = $collection->search('4', true);5 6// 37$key = $collection->search(4, true);
∎
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.