Skip to content

Instantly share code, notes, and snippets.

@jondlm
Last active July 18, 2021 02:37
Show Gist options
  • Save jondlm/7709e54f84a3f1e1b67b to your computer and use it in GitHub Desktop.
Save jondlm/7709e54f84a3f1e1b67b to your computer and use it in GitHub Desktop.
Recursive array diff php
<?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;
}
@stefanandreaslarsson
Copy link

Recursively thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment