Reputation: 3193
I have a simple collection that I want to filter. Take the following example:
// Create an array of fruits
$array = ["banana", "apple", "orange"];
// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($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);
Works great assuming I only ever want to filter by 'banana'. What if I want to use a variable within the filter. How do I do that?
// Create an array of fruits
$array = ["banana", "apple", "orange"];
$filterby = 'apple';
// Transform the array into a Collection object
$collection = new Illuminate\Support\Collection($array);
// We don't like banana's anymore, so we're going to filter them out
$filtered = $collection->filter(function($element) {
if ($element != $filterby) return true;
});
// Dump out our array now, and we'll see the banana's are gone
dd($filtered);
The above won't work because $filterby
isn't available in the filter()
function. How would I make it available?
Upvotes: 1
Views: 1509
Reputation: 281
You can 'use' this variable TH1981, like this
$filtered = $collection->filter(function($element) use ($filterby) {
return $element != $filterby;
});
and one more tip you can make a collect with this global method
$collection = collect($array);
Upvotes: 1