Skip to content

Instantly share code, notes, and snippets.

@jqlblue
Created August 12, 2016 03:17
Show Gist options
  • Save jqlblue/dd913448bd85eeda9706379404c8057c to your computer and use it in GitHub Desktop.
Save jqlblue/dd913448bd85eeda9706379404c8057c to your computer and use it in GitHub Desktop.
php array diff recursive
function diffRecursive($from, $to, $deleteFlag = false)
{
$diffs = [];
foreach ($from as $key => $value) {
if (array_key_exists($key, $to)) {
if (is_array($value)) {
$recursiveDiff = diffRecursive($value, $to[$key], $deleteFlag);
if (! empty($recursiveDiff)) {
$diffs[$key] = $recursiveDiff;
}
} else {
if ($value != $to[$key] && ! $deleteFlag) {
$diffs[$key] = 'modify';
}
}
} else {
if ($deleteFlag) {
$diffs[$key] = 'delete';
} else {
$diffs[$key] = 'add';
}
}
}
return $diffs;
}
$a = [
'a' => [
'key1' => 1,
'key2' => 2,
],
'b'=> [
'bkey1' => [
'bbkey1' => 'bb1',
'bbkey2' => 'bb2',
]
]
];
$b = [
'a' => [
'key1' => 2,
'key3' => 2,
],
'b'=> [
'bkey1' => [
'bbkey1' => 'bb1',
'bbkey2' => 'bb2',
]
]
];
$s1 = diffRecursive($a, $b);
var_dump($s1);
$s2 = diffRecursive($b, $a, true);
var_dump($s2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment