Home » Php » PHP get difference of two arrays of objects

PHP get difference of two arrays of objects

Posted by: admin April 23, 2020 Leave a comment

Questions:

I know there is array_diff and array_udiff for comparing the difference between two arrays, but how would I do it with two arrays of objects?

array(4) {
    [0]=>
        object(stdClass)#32 (9) {
            ["id"]=>
            string(3) "205"
            ["day_id"]=>
            string(2) "12"
        }
}

My arrays are like this one, I am interested to see the difference of two arrays based on IDs.

How to&Answers:

This is exactly what array_udiff is for. Write a function that compares two objects the way you would like, then tell array_udiff to use that function. Something like this:

function compare_objects($obj_a, $obj_b) {
  return $obj_a->id - $obj_b->id;
}

$diff = array_udiff($first_array, $second_array, 'compare_objects');

Or, if you’re using PHP >= 5.3 you can just use an anonymous function instead of declaring a function:

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return $obj_a->id - $obj_b->id;
  }
);

Answer:

And here is another option if you wanna compare string properties (e.g. name):

$diff = array_udiff($first_array, $second_array,
  function ($obj_a, $obj_b) {
    return strcmp($obj_a->name, $obj_b->name);
  }
);

Answer:

Here’s another option, if you want to run the diff according to object instances. You would use this as your callback to array_udiff:

function compare_objects($a, $b) {
    return strcmp(spl_object_hash($a), spl_object_hash($b));
}

You’d only want to use that if you’re certain that the arrays both contain only objects – here’s my personal use case.