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.

<?php

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(
    $objects1,
    $objects2,
    function ($object1, $object2) {
        if ($object1 and $object2) {
            return $object1->value - $object2->value;
        }
    }
);

print_r($uniqueObjects);

This prints the following.

Array
(
    [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.
CAPTCHA
4 + 2 =
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.