Today’s array difference puzzle, you’d think, would be trivial. In many languages it is.

Ali Spittel‘s Python solution, for example:

Ali's Python arrayDiff solution

In PHP, at first, it seems trivial. We have an array_diff() function. Just wrap it and return:

PHP arrayDiff, first try

But not so fast!

Under the hood, PHP arrays are actually hash tables. So when you run the unit test on this, it won’t pass!

PHP arraydiff unit test failing

The array keys in $arrayA are preserved in the resulting hash table. To get this to pass, you have to re-key the array!

There are 2 ways to do it. The first way that comes to mind is go through item by item and move the values into a fresh array starting at the zero key. But even more clever is to run the result of array_diff() through the array_values() function. Both methods are shown below.

PHP arrayDiff solution