April 22, 2018 —John Koster
The diffKeys
method is similar to the diff
method. It is used to determine which items whose keys in the collection are not present in the supplied $items
collection's keys. $items
can be either an array, or another instead of Collection
.
1public function diffKeys(2 $items3);
The following example shows the basic usage of the diffKeys
method:
1$firstCollection = collect([ 2 'name' => 'Shiny New Tablet', 3 'price' => 799.99 4]); 5 6$secondCollection = collect([ 7 'name' => 'Shiny New Tablet', 8 'description' => 'Much shinier and bigger!' 9]);10 11$differences = $firstCollection12 ->diffKeys($secondCollection);
After the code has executed the $differences
variable would contain a value similar to the following:
1Collection {2 #items: array [3 "price" => 799.994 ]5}
The result only contains the item price
, because that is the only item in the $firstCollection
that was not present in the $secondCollection
.
If we had reversed the order of the collections to the following:
1$firstCollection = collect([ 2 'name' => 'Shiny New Tablet', 3 'price' => 799.99 4]); 5 6$secondCollection = collect([ 7 'name' => 'Shiny New Tablet', 8 'description' => 'Much shinier and bigger!' 9]);10 11$differences = $secondCollection12 ->diffKeys($firstCollection);
this would be the value returned:
1Collection {2 #items: array [3 "description" => "Much shinier and bigger!"4 ]5}
∎
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.