A common problem is having a collection of items that all need to meet a certain criteria. In the example below we have collected two items for a diet plan and we want to check that the diet doesn't contain any unhealthy food.
// First we create a collection
$diet = collect([
['name' => 'Banana', 'calories' => '89'],
['name' => 'Chocolate', 'calories' => '546']
]);
// Then we check the collection for items with more than 100 calories
$isUnhealthy = $diet->contains(function ($i, $snack) {
return $snack["calories"] >= 100;
});
In the above case the $isUnhealthy
variable will be set to true
as Chocolate meets the condition, and the diet is thus unhealthy.