Skip to content

Instantly share code, notes, and snippets.

@VitalyKondratiev
Created July 19, 2019 09:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VitalyKondratiev/ec3f12c504dd6b531cc0c0e275d6d3e7 to your computer and use it in GitHub Desktop.
Save VitalyKondratiev/ec3f12c504dd6b531cc0c0e275d6d3e7 to your computer and use it in GitHub Desktop.
PHP: Recursive difference finder of 2 objects
<?php
function _arrd($array1, $array2, $label, $depth = 0, $has_diff = false) {
$array1 = (array)$array1;
$array2 = (array)$array2;
if (!$depth) {
$label .= ': ';
}
$diff = array_diff_assoc($array1, $array2);
if (count($diff)) {
echo "$label\n";
foreach ($diff as $diff_key => $diff_value) {
$left_diff = !is_null($diff_value) ? $diff_value : 'null';
$right_diff = !is_null($array2[$diff_key]) ? $array2[$diff_key] : 'null';
echo "\t$diff_key: $left_diff != $right_diff\n";
}
$has_diff = true;
}
foreach ($array1 as $key => $item) {
if (is_array($item)) {
$has_diff = _rd($array1[$key], $array2[$key], $label . "[$key]", $depth + 1, $has_diff);
}
}
if (!$has_diff && !$depth) {
echo "${label}nasn't diff\n";
}
return ($has_diff) ? true : $has_diff;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment