Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get difference of two arrays of objects

Tags:

arrays

php

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.

like image 226
roflwaffle Avatar asked Jun 24 '11 18:06

roflwaffle


People also ask

How can I find the difference between two arrays in PHP?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.

How do I check if two arrays have the same element in PHP?

Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important.

How can I get unique values from two arrays in PHP?

The array_diff() (manual) function can be used to find the difference between two arrays: $array1 = array(10, 20, 40, 80); $array2 = array(10, 20, 100, 200); $diff = array_diff($array1, $array2); // $diff = array(40, 80, 100, 200);


1 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;   } ); 
like image 93
Jordan Running Avatar answered Oct 05 '22 21:10

Jordan Running