====== Multi Dimensional Array Compare ======
This function compares two multi dimensional arrays and returns an array containing the new, removed and changed values as separate array.
[],
'removed' => [],
'changed' => []
];
// Check for new and changed values
foreach ($array2 as $key => $value) {
if (array_key_exists($key, $array1)) {
if (is_array($value) && is_array($array1[$key])) {
$recursiveResult = compareArrays($array1[$key], $value);
if (!empty($recursiveResult['new'])) {
$result['new'][$key] = $recursiveResult['new'];
}
if (!empty($recursiveResult['removed'])) {
$result['removed'][$key] = $recursiveResult['removed'];
}
if (!empty($recursiveResult['changed'])) {
$result['changed'][$key] = $recursiveResult['changed'];
}
} elseif ($value !== $array1[$key]) {
$result['changed'][$key] = [
'old' => $array1[$key],
'new' => $value
];
}
} else {
$result['new'][$key] = $value;
}
}
// Check for removed values
foreach ($array1 as $key => $value) {
if (!array_key_exists($key, $array2)) {
$result['removed'][$key] = $value;
}
}
return $result;
}
Example usage:
$array1 = [
'name' => 'John',
'age' => 30,
'address' => [
'city' => 'New York',
'state' => 'NY'
],
'hobbies' => ['reading', 'traveling']
];
$array2 = [
'name' => 'John',
'age' => 31,
'address' => [
'city' => 'San Francisco',
'state' => 'CA'
],
'hobbies' => ['reading', 'sports'],
'profession' => 'Developer'
];
$differences = compareArrays($array1, $array2);
print_r($differences);
?>