Laravel 5 Collections: Filtering Collection Elements Using Strict Comparison Operators With whereStrict

April 22, 2018 —John Koster

The whereStrict method is similar to the where method, but it will always use strict comparisons when determining the results to return.

#Signature

1public function whereStrict(
2 $key,
3 $value
4);

#Example Use

The $sampleCollection collection instance will be used in the following examples:

1$sampleCollection = collect([
2 [
3 'name' => 'Desk',
4 'price' => 499.99
5 ],
6 [
7 'name' => 'Office Chair',
8 'price' => '499.99'
9 ]
10]);

If you noticed, the first product (Desk) has its price specified as a float value, and the second product (Office Chair) has its specified as a string.

The following example are behaviorally equivalent:

1$products = $sampleCollection
2 ->where('price', '===', 499.99, true);
3 
4$products = $sampleCollection
5 ->whereStrict('price', 499.99);

In both bases in the previous example, the $products collection would only contain the product Desk; this is because the whereStrict method (as well as the where method when the $operator is set to ===) will compare the types on both sides of the comparison operator.

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.