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

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

Laravel 5

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

public function containsStrict(
    $key,
    $value = null
);

Example Use

The following examples demonstrate the behavior of the containsStrict method:

$prices = collect([
    '9.99',
    '19.99',
    '14.99',
]);

$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:

$products = collect([
    [
        'name' => 'Office Chair',
        'price' => 419.99
    ],
    [
        'name' => 'Wooden Desk',
        'price' => 699.99
    ]
]);

$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.

Start the Discussion

Leave a comment

Subscribe to our newsletter