Search

Laravel 5 Collections: Returning Collection Elements That Are Not Present in the Specified Collections With diffAssoc

April 22, 2018 —John Koster

The diffAssoc method will return the items in the collection where the keys and items are not present in the provided arguments. This method does not modify the original collection; it will return a new collection instance containing the different items.

The diffAssoc exhibits similar behavior to PHP's array_diff_assoc function.

#Signature

1public function diffAssoc(
2 $items
3);

#Example Use

The following example highlights the usage of the diffAssoc method; we will start with a collection of user-supplied information (stored in $contactInformation) that we will compare with the information we already know about the user. We will store any new information in a variable named $newInformation:

1$contactInformation = collect([
2 'firstName' => 'John',
3 'lastName' => 'Doe',
4 'middleName' => 'Calvin'
5]);
6 
7$newInformation = $contactInformation->diffAssoc([
8 'firstName' => 'John',
9 'lastName' => 'Doe',
10]);

After the above example has executed, the $newInformation variable would contain a new collection instance with data similar to the following output:

1Collection {
2 #items: array [
3 "middleName" => "Calvin"
4 ]
5}

Some absolutely amazing
people

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.