Hello Laravel developers! In Laravel, working with collections is even more powerful and intuitive. Today, we'll explore two useful methods available in Laravel's Collection class: contains() and containsStrict(). These methods allow you to check if a collection contains a specific value. Let's dive in and see how they work with some examples!
contains() Method:
The contains() method checks if a collection contains a given value. It returns true if the value is found, and false otherwise. Here's an example:
$numbers = collect([1, 2, 3, 4, 5]);
$containsThree = $numbers->contains(3);
// Output: true
In the above example, we create a collection of numbers and use the contains() method to check if the collection contains the value 3. Since 3 is present in the collection, the contains() method returns true.
containsStrict() Method:
The containsStrict() method works similarly to contains(), but it performs a strict comparison, including both the value and the data type. Here's an example:
$fruits = collect(['apple', 'banana', 'cherry']);
$containsNumber = $fruits->containsStrict(5);
// Output: false
In this example, we have a collection of fruits and use the containsStrict() method to check if the collection contains the value 5. Since 5 is not present in the collection, and it's a different data type than the string values, the method returns false.
Additional Example:
Here's another example demonstrating the use of the contains() method with a custom callback function:
$users = collect([
['name' => 'John', 'age' => 25],
['name' => 'Jane', 'age' => 30],
['name' => 'Alice', 'age' => 35],
]);
$containsJane = $users->contains(function ($user) {
return $user['name'] === 'Jane';
});
// Output: true
In this example, we create a collection of users and use the contains() method with a callback function to check if the collection contains a user with the name 'Jane'. The callback function compares the name of each user with the desired value, and since 'Jane' is present in the collection, the method returns true.