Created
July 12, 2019 12:27
-
-
Save xZero707/854a8b48a96539505634aa213f717f8f to your computer and use it in GitHub Desktop.
Compares two arrays and shows exact difference between them. The ultimate function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Compares two arrays and shows exact difference between them. | |
* | |
* !!! IMPORTANT !! | |
* Order of two supplied arrays matters! | |
* | |
* @fix xZero707 <[email protected]>: Pay attention to types as well | |
* | |
* [NOTE BY danbrown AT php DOT net: The array_diff_assoc_recursive function is a | |
* combination of efforts from previous notes deleted. | |
* Contributors included (Michael Johnson), (jochem AT iamjochem DAWT com), | |
* (sc1n AT yahoo DOT com), and (anders DOT carlsson AT mds DOT mdh DOT se).] | |
* | |
* @param array $array1 | |
* @param array $array2 | |
* @return array|int | |
*/ | |
function array_diff_assoc_recursive(array $array1, array $array2) | |
{ | |
foreach ($array1 as $key => $value) { | |
if (is_array($value)) { | |
if (!array_key_exists($key, $array2)) { | |
$difference[$key] = $value; | |
} elseif (!is_array($array2[$key])) { | |
$difference[$key] = $value; | |
} else { | |
$new_diff = $this->array_diff_assoc_recursive($value, $array2[$key]); | |
if ($new_diff != FALSE) { | |
$difference[$key] = $new_diff; | |
} | |
} | |
} elseif (!array_key_exists($key, $array2) || $array2[$key] != $value) { | |
$difference[$key] = $value; | |
} | |
} | |
return (!isset($difference) ? 0 : $difference); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment