PHP question: how to solve array_intersect_assoc () array recursively

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);

Printed Result:

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

Clear that the values ​​associated with "key2" in both arrays do not match, however array_intersect_assoc() still returns 'key2' => 'value2' as the traversed value.

Is this the expected behavior of array_intersect_assoc() ?

Thanks!

+6
arrays php multidimensional-array
source share
1 answer

Yes, this is the expected behavior, because the comparison is performed using string representations, and the function does not regress nested arrays. From manual :

Two values ​​from the key => pairs are considered equal only if (string) $ elem1 === (string) $ elem2. In other words, strict type checking is done, so the string representation should be the same.

If you try to traverse the array using 'key1' => 'Array' , you will get the same result, because the string representation of the array is always 'Array' .

One of the notes made by the user , according to nleippe, contains a recursive implementation that looks promising (I changed the third line to compare strings for any values ​​without an array):

 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; } 
+6
source share

All Articles