I'm looking for an efficient way of comparing two arrays in PHP. I have a "before" and an "after" array, and I need to get arrays of specific changes. I did manage to get part of the code right (not sure about how effective it is), but I just can't seem to get the last comparison to work.
The first part of every element is essentially an ID, which stays the same even if the second element, essentially a Name, is changed - note Name1-Renamed for example. The ID is the same. Sometimes an element might be removed (see ID 1233, 'Name3-Deleted' is only in the 'before' array) or added (as in the case of ID 1230, 'Name4-New'). Also note that IDs, while unique, are NOT sorted in any particular order.
So, I would need to find the items that have been - Added (available 'after', but not 'before') - Removed (available 'before', but not 'after') - Changed (available in both, as there is an ID match, but the Name has changed)
And I can't for the life of me find an effective way to get the Changed elements (preferably without ifs or extraneous loops). Also, what do you think? Is array_udiff the fastest/best method for this particular task?
<?php
//'BEFORE' ARRAY
$arr1 = array( array(1231, 'Name1'), array(1232, 'Name2'), array(1233, 'Name3-Deleted') );
//'AFTER' ARRAY
$arr2 = array( array(1231, 'Name1-Renamed'), array(1232, 'Name2'), array(1230, 'Name4-New') );
//'ADDED' ARRAY
$arr3 = array_udiff($arr2, $arr1, create_function(
'$a,$b',
'return $a[0] - $b[0]; ')
);
//'REMOVED' ARRAY
$arr4 = array_udiff($arr1, $arr2, create_function(
'$a,$b',
'return $a[0] - $b[0]; ')
);
//'CHANGED' ARRAY. CAN'T GET THIS TO WORK PROPERLY. EXPECTED RESULT IS AN ARRAY FOR THE RENAMED ITEM.
$arr5 = array_udiff($arr2, $arr1, create_function(
'$a,$b',
'return (strcmp($a[1],$b[1]))*(strcmp($a[0],$b[0])); ')
);
print("Elements Added\n");
print_r($arr3);
print("Elements Removed\n");
print_r($arr4);
print("Elements Renamed\n");
print_r($arr5);
?>
So, that is pretty much it. Does anybody know how to fix this issue? Thanks in advance for all your help!