November 29, 2016 —John Koster
diffKeys($items)
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
.
The following example shows the basic usage of the diffKeys
method:
1<?php2 3$firstCollection = collect(['name' => 'Shiny New Tablet', 'price' => 799.99]);4$secondCollection = collect(['name' => 'Shiny New Tablet', 'description' => 'Much shinier and bigger!']);5 6$differences = $firstCollection->diffKeys($secondCollection);
After the code has executed the $differences
variable would contain a value similar to the following:
1Collection {2 #items: array:1 [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<?php2 3$firstCollection = collect(['name' => 'Shiny New Tablet', 'price' => 799.99]);4$secondCollection = collect([5 'name' => 'Shiny New Tablet',6 'description' => 'Much shinier and bigger!'7]);8 9$differences = $secondCollection->diffKeys($firstCollection);
this would be the value returned:
1Collection {2 #items: array:1 [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.