Find The Difference Between Two Arrays Of Objects In PHP

Use the array_udiff() function to create a unique array of objects from two lists of arrays.


class ValueObject {
    public int $value;
    public function __construct($value) {
        $this->value = $value;

$objects1 = [];
$objects1[] = new ValueObject(1);
$objects1[] = new ValueObject(2);
$objects1[] = new ValueObject(3);

$objects2 = [];
$objects2[] = new ValueObject(1);
$objects2[] = new ValueObject(2);

// Filter out any duplicate objects.
$uniqueObjects = array_udiff(
    function ($object1, $object2) {
        if ($object1 and $object2) {
            return $object1->value - $object2->value;


This prints the following.

    [2] => ValueObject Object
            [value] => 3


Our new array contains the object with the value of 3, which was only present in one of the original arrays.

Add new comment

The content of this field is kept private and will not be shown publicly.
2 + 7 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.