Published in Laravel

Laravel Collection Public API: diff

By John Koster

diff($items)

The diff method is used to determine which items in the collection are not present in the supplied $items collection. $items can be be either an array, or another instance of Collection. The diff method returns a new instance of Collection.

The following examples will demonstrate the usage of the diff:

1<?php
2
3use Illuminate\Support\Collection;
4
5// Create the first collection instance.
6$firstCollection = new Collection([
7 'first', 'second', 'third'
8]);
9
10// Create the second collection instance.
11$secondCollection = new Collection([
12 'third', 'fourth', 'fifth'
13]);
14
15// ['first', 'second']
16$firstCollection->diff(['third', 'fourth', 'fifth']);
17
18// ['first', 'second']
19$firstCollection->diff($secondCollection);
20
21// ['fourth', 'fifth']
22$secondCollection->diff($firstCollection);