Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

I've got two arrays, for which var_dump give 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 countaining only the second elements. Instead I got an empty array. I try switching the parameters, and still an empty_array, but this time without surprise. Wouldn't array_diff work on arrays of arrays?

like image 715
Eldros Avatar asked Dec 28 '22 01:12

Eldros


2 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(); gives you just Array, so for array_diff, your arrays look like:

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

So to create a diff for your arrays, you would need something like this (assuming that every element in the arrays is itself 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.

like image 139
Felix Kling Avatar answered Mar 08 '23 05:03

Felix Kling


From the array_diff documentation.

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

like image 36
xzyfer Avatar answered Mar 08 '23 07:03

xzyfer