Search

Laravel 5 Collections: Determining if a Collection Contains an Element Using Strict Comparison With containsStrict

April 22, 2018 —John Koster

The containsStrict method is similar to the contains method; it acts as a shortcut to calling the contains method with a strict comparison operator.

#Signature

1public function containsStrict(
2 $key,
3 $value = null
4);

#Example Use

The following examples demonstrate the behavior of the containsStrict method:

1$prices = collect([
2 '9.99',
3 '19.99',
4 '14.99',
5]);
6 
7$contains = $prices->containsStrict(9.99);

After the above code has executed, the value of the $contains variable would be false; this is because our collection contains string values and we are supplying a float value for our comparison value. If we replaced the line with $prices->containsStrict('9.99'), the containsStrict method would have returned true.

The following example demonstrates the containsStrict method when specifying both a key and value:

1$products = collect([
2 [
3 'name' => 'Office Chair',
4 'price' => 419.99
5 ],
6 [
7 'name' => 'Wooden Desk',
8 'price' => 699.99
9 ]
10]);
11 
12$contains = $products->containsStrict('price', 699.99);

Since the $products collection does in fact contain a price key with the value 699.99, the $contains variable would contain the value true.

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.