Why does array_diff on arrays of arrays return an empty array?

I have two arrays for which var_dump gives the following values:

$ array1:

Artifacts:array(2) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } [1]=> array(3) { [0]=> string(7) "module2" [1]=> string(17) "path/to/file2.txt" [2]=> string(0) "" } } 

$ array2:

 Artifacts:array(1) { [0]=> array(3) { [0]=> string(7) "module1" [1]=> string(16) "path/to/file.txt" [2]=> string(0) "" } } 

I would think that doing array_diff($array1,$array2) would give me an array containing only two elements. Instead, I got an empty array. I'm trying to switch parameters, and still empty_ariths, but this time without surprise. Will array_diff work with arrays of arrays?

+4
source share
4 answers

From the documentation :

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

echo (string) array(); only gives you Array , so for array_diff your arrays look like this:

 $array1 = array('Array', 'Array'); $array2 = array('Array'); 

So, to create a diff for your arrays, you need something like this (assuming that each element of the array itself is an array):

 $diff = array(); foreach($array1 as $val1) { $contained = false; foreach($array2 as $val2) { if(count(array_diff($val1, $val2)) == 0) { $contained = true; break; } } if(!$contained) { $diff[] = $val1; } } 

Disclaimer: This is more or less just a sketch.

+5
source

See the documentation for array_diff .

This function checks only one dimension of an n-dimensional array. Of course, you can check for deeper dimensions using array_diff ($ array1 [0], $ array2 [0]);

+3
source

On the array_diff manual page: "This function only checks one dimension of an n-dimensional array. Of course, you can check for deeper dimensions using array_diff ($ array1 [0], $ array2 [0]) ;."

0
source

Answered and answered here:

recursive array_diff ()?

0
source

Source: https://habr.com/ru/post/1339161/


All Articles