November 30, 2016 —John Koster
reject($callback)
The reject
method used to create a new Collection
instance containing all the items in the collection that do not pass a given truth test. The reject
method only defines one parameter: $callback
. The $callback
function should only have one parameter $item
, which will contain the collection item under test. The $callback
should return true
if the item should not be included in the final collection.
To put it another way, the $callback
function answers the question "Should I remove this item from the collection?" true
means it will be removed, false
indicates that it should remain in the collection.
The following code example demonstrates the usage of the reject
method by rejecting any name that does not begin with the letter a
(ignoring case):
1<?php 2 3use Illuminate\Support\Collection; 4use Illuminate\Support\Str; 5 6// Create a new collection instance. 7$collection = new Collection([ 8 'Alice', 'Anna', 'Bob', 'Bev' 9]);10 11// Only keep names that begin with the letter 'a'.12$names = $collection->reject(function($item), {13 return !Str::startsWith(Str::lower($item), 'a');14});
After the above code executes, the $names
variable will be an instance of Collection
and contain a value similar to the following output:
1object(Illuminate\Support\Collection)[136]2 protected 'items' =>3 array (size=2)4 0 => string 'Alice' (length=5)5 1 => string 'Anna' (length=4)
∎
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.