recursive array_diff()?

✔ Recommended Answer

There is one such function implemented in the comments of array_diff.

function arrayRecursiveDiff($aArray1, $aArray2) {  $aReturn = array();  foreach ($aArray1 as $mKey => $mValue) {    if (array_key_exists($mKey, $aArray2)) {      if (is_array($mValue)) {        $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);        if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }      } else {        if ($mValue != $aArray2[$mKey]) {          $aReturn[$mKey] = $mValue;        }      }    } else {      $aReturn[$mKey] = $mValue;    }  }  return $aReturn;} 

The implementation only handles two arrays at a time, but I do not think that really posses a problem. You could run the diff sequentially if you need the diff of 3 or more arrays at a time. Also this method uses key checks and does a loose verification.


Answered By: mhitza

Method #2

There is no built-in function for recursively finding the difference between two multidimensional arrays in PHP, but you can create a custom function using recursion. Here's an example implementation of a recursive array_diff() function:

function recursive_array_diff($array1, $array2) { $diff = array(); foreach($array1 as $key => $value) { if(is_array($value)) { if(!isset($array2[$key]) || !is_array($array2[$key])) { $diff[$key] = $value; } else { $new_diff = recursive_array_diff($value, $array2[$key]); if(!empty($new_diff)) { $diff[$key] = $new_diff; } } } else { if(!array_key_exists($key, $array2) || $array2[$key] !== $value) { $diff[$key] = $value; } } } return $diff; }

In this implementation, we use a recursive approach to iterate through each element of the first array and compare it to the corresponding element in the second array. If the element is an array, we call the function recursively to compare the sub-arrays. If the element is a scalar value, we compare it directly to the corresponding element in the second array.

The function returns an array of the differences between the two arrays. If an element exists in the first array but not the second, it will be included in the result array. If an element exists in both arrays but has different values, it will also be included in the result array.

Note that this implementation assumes that the arrays are indexed by string keys. If your arrays use numeric keys, you may need to modify the function to handle this case.


Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755