Last active
July 18, 2021 02:37
-
-
Save jondlm/7709e54f84a3f1e1b67b to your computer and use it in GitHub Desktop.
Recursive array diff php
This file contains 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 | |
/* | |
* Recursively diff two arrays. This function expects the leaf levels to be | |
* arrays of strings or null | |
*/ | |
function diff_recursive($array1, $array2) { | |
$difference=array(); | |
foreach($array1 as $key => $value) { | |
if(is_array($value) && isset($array2[$key])){ // it's an array and both have the key | |
$new_diff = diff_recursive($value, $array2[$key]); | |
if( !empty($new_diff) ) | |
$difference[$key] = $new_diff; | |
} else if(is_string($value) && !in_array($value, $array2)) { // the value is a string and it's not in array B | |
$difference[$key] = $value . " is missing from the second array"; | |
} else if(!is_numeric($key) && !array_key_exists($key, $array2)) { // the key is not numberic and is missing from array B | |
$difference[$key] = "Missing from the second array"; | |
} | |
} | |
return $difference; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks! Perfect