Laravel collection contain method like php in_array()

What is use of Laravel collection contains method. php in_array() equivalent method in collection. How to check a value exist in laravel collection.


Laravel collection contains method

laravel collection contains method work like php in_array() function. Collection contains method check given value exist or not in collection.

$collection = collect(['name' => 'Anmol', 'age' => 25]);
 
$collection->contains('Anmol');
// true
 
$collection->contains('Alok');
// false

You can also check your data by key-value pair. It determine given key-value data exist in collection.

$collection = collect([
    ['name' => 'Anmol', 'age' => 25],
    ['name' => 'Alok', 'age' => 23],
]);
 
$collection->contains('name', 'Alok');
// true

Laravel contains methods also check a given condition data exist or not in collection

$collection = collect([1, 2, 3, 4, 5, 6]);
 
$collection->contains(function ($value, $key) {
    return $value > 6;
});
// false
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links