1

I have two multidemensional arrays and I am trying to use array_intersect to find the values from $array1 that occur in $array2. Instead the results, as you can see below, include both values from the first array $array1 even though only one of the values occurs in the second array $array2. I suppose I have some misunderstanding of how this function works, can anyone clarify what I am doing wrong here?

var_dump($array1);
array(2) {
  [0]=>
  array(1) {
    ["id"]=>
    string(2) "28"
  }
  [7]=>
  array(1) {
    ["id"]=>
    string(2) "30"
  }
}

var_dump($array2);
array(1) {
  [0]=>
  array(1) {
    ["id"]=>
    string(2) "30"
  }
}


var_dump(array_intersect($array1, $array2));
array(2) {
  [0]=>
  array(1) {
    ["id"]=>
    string(2) "28"
  }
  [7]=>
  array(1) {
    ["id"]=>
    string(2) "30"
  }
}
cantaffordavan
  • 1,427
  • 4
  • 24
  • 44

2 Answers2

0

The function array_intersect compares the values as strings, see manual. Unfortunately, this gives simply "Array" for all arrays.

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation
is the same.

Instead you can use a custom compare function:

array_uintersect($array1, $array2, function($a, $b) { return ($a<$b)?-1:($a==$b)?0:1; })

Or use !== if you want to also compare order and types - see here for the difference.

AdamS
  • 209
  • 2
  • 8
-1

array_intersect_assoc() looks at key and value for intersection.

helloandre
  • 10,541
  • 8
  • 47
  • 64