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

1 min read

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.

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch