Using array_diff with Nested Arrays

Posted on Updated on Laravel by Gergő D. Nagy

We often post about tricks and hacks for PHP’s arrays. Here we come with another one again. Let’s use array_diff for deeper arrays as well, with the help of Laravel’s Arr class.

The array_diff function is very useful when we are trying to compare arrays and work with them. The problem is, like many comparing function, this one is working with one level as well.

If you want to get the matching elements from two arrays, you can use array_intersect.

With the help of Laravel’s Arr::dot(), we can flatten our arrays and generate unique keys that represent the “position” of the values, while our array has only one level. Then we can use array_diff to compare our arrays.

$a1 = ['one' => 'two'];
$a2 = ['one' => 'two', 'three' => ['four' => 'five']];

Arr::dot($a2); // ['one' => 'two', 'three.four' => 'five']

$diff = array_diff($a1, $a2); // ['three.four' => 'five']

If we want, we can convert the flattened array back easily, so we can have the original array structure, but holding only the differentiated values.

$a = array_reduce(array_flip($diff), function ($carry, $key) use ($diff) {
    Arr::set($carry, $key, $diff[$key]);

    return $carry;
}, []);

It’s a simple yet powerful solution that we can use easily. Of course, you can do the same with array_intersect as well.

Need a web developer? Maybe we can help, get in touch!