November 29, 2016 —John Koster
filter(callable $callback = null)
The filter
method applies a filter to the collection. An optional $callback
can be supplied to the filter
method. If no $callback
is supplied to the filter
method, any value in the collection that evaluates to false
will be removed from the final collection. Supplying a $callback
allows developers to provide their own truth tests to determine if a value should be included in the final collection that is returned. The filter
method returns a modified copy of the original Collection
instance and does not modify the original collection.
1<?php 2 3use Illuminate\Support\Collection; 4 5// Create a new collection instance. 6$collection = new Collection([ 7 'first', 'second', '0', null 8]); 9 10// ['first', 'second']11$filtered = $collection->filter();12 13// ['0', null]14$filtered = $collection->filter(function($item) {15 return $item == false;16});17 18// ['second']19$filtered = $collection->item(function($item) {20 return (strlen($item) >= 6);21});
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.