phparraysmultidimensional-arrayfilterassociative-array

How to recursively implement array_intersect_assoc() on multidimensional associative arrays


Let's say I want to do this:

$a = array_intersect_assoc(
 array(
  'key1' => array(
   'key2' => 'value2'
  ),
  'key3' => 'value3',
  'key4' => 'value4'
 ),
 
 array(
  'key1' => array(
   'key2' => 'some value not in the first parameter'
  ),
  'key3' => 'another value'
 )
);

var_dump( $a );

The printed result is:

array
  'key1' => 
    array
      'key2' => string 'value2' (length=6)

It's clear that values associated with 'key2' in both arrays are not the same, however array_intersect_assoc() still return 'key2' => 'value2' as the intersected value.

Is this the expected behavior of array_intersect_assoc()?

Thanks!


Solution

  • Yes, it's the expected behavior, because the comparison is done using string representations, and the function does not recurse down nested arrays. From the manual:

    The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same.

    If you tried to intersect with an array with 'key1' => 'Array', you'd get the same result because the string representation of an array is always 'Array'.

    One of the user-contributed notes, by nleippe, contains a recursive implementation that looks promising (I modified the third line to do string comparison on any non-array values):

    function array_intersect_assoc_recursive(&$arr1, &$arr2) {
        if (!is_array($arr1) || !is_array($arr2)) {
    //      return $arr1 == $arr2; // Original line
            return (string) $arr1 == (string) $arr2;
        }
        $commonkeys = array_intersect(array_keys($arr1), array_keys($arr2));
        $ret = array();
        foreach ($commonkeys as $key) {
            $ret[$key] =& array_intersect_assoc_recursive($arr1[$key], $arr2[$key]);
        }
        return $ret;
    }