Laravel: Filter Every Array Element with a Closure

I always forget about how awesome Laravel Collection’s are. I came across this gem when needing to run a filter on every element of an array. I think it may of been Dayle’s book that first informed me of them. For example, if you have an array of fruits that you want to filter down, you can do the following:

// Create an array of fruits
$array = ["banana", "apple", "orange"];

// Transform the array into a Collection object
$collection = new IlluminateSupportCollection($array);

// We don’t like banana’s anymore, so we’re going to filter them out
$no_bananas = $collection->filter(function($element) {
if ($element != “banana”) return true;
});

// Dump out our array now, and we’ll see the banana’s are gone
dd($no_bananas);