I have two arrays that contain objects:
array $a (size=2)
0 =>
object(A)
private '_id' => int 10
1 =>
object(A)
private '_id' => int 11
array $b (size=1)
0 =>
object(B)
private '_id' => int 10
I'm trying to find which item in array $a
doesn't exist in array $b
, which in this case is $a[1]
. Looping both arrays can do this, but I would like a more effective way.
My Answer:
One way to achieve this is by using array_udiff() function in PHP. This function compares two arrays and returns the values from the first array that are not present in the second array based on a user-defined comparison function.
Here's an example of how you can use array_udiff() to find the items in array $a that don't exist in array $b:
php
function compareObjects($a, $b) {
return $a->_id - $b->_id;
}
$diff = array_udiff($a, $b, 'compareObjects');
print_r($diff);
In this example, the compareObjects() function compares the objects based on their '_id' property. The array_udiff() function then returns the objects from array $a that are not present in array $b based on this comparison function.
After running this code, the $diff array will contain the object from array $a that doesn't exist in array $b.
Rate this post
5 of 5 based on 3446 votesComments