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