DEV Community

Martin Himmel
Martin Himmel

Posted on

A Tale of an Array Conversion Bug

In light of a Tweet from Ben, I thought I'd share a recent bug story.

Moving array data from PHP to JavaScript is something I do regularly. Sometimes it's key/value pairs, other times it's a simple list of values.

In this particular instance, I needed an intersection of two arrays.

Here's a contrived example:

$main_colors = ['yellow', 'blue', 'orange', 'brown'];
$other_colors = ['pink', 'purple', 'blue', 'brown'];
$intersection = array_intersect($main_colors, $other_colors);
Enter fullscreen mode Exit fullscreen mode

It's then passed back to JavaScript as json_encode($intersection);.

On the JavaScript side, an array of values was expected, however, it received an object.

Wait... What?

It didn't take too long to realize what the issue was, but longer than I care to admit. πŸ˜†

array_intersect maintains the first array's index order. In other words, $intersection is an array, structured as:

[1] => 'blue',
[3] => 'brown'
Enter fullscreen mode Exit fullscreen mode

Which translates to an object in JavaScript:

{
  "1": "blue",
  "3": "brown"
}
Enter fullscreen mode Exit fullscreen mode

Because the index numbers are maintained in the intersection, instead of it being a list of values, it becomes a list of key/value pairs.

The fix is easy enough, using array_values, which returns all the values of an array.

$intersection = array_values(array_intersect($main_colors, $other_colors));
Enter fullscreen mode Exit fullscreen mode

In PHP, $intersection is restructured as an ordered/indexed array:

[0] => 'blue',
[1] => 'brown'
Enter fullscreen mode Exit fullscreen mode

And when that's encoded (using json_encode) for JavaScript's usage, it looks like:

['blue', 'brown']
Enter fullscreen mode Exit fullscreen mode

Which is what I was expecting in the first place. πŸ˜€

Top comments (1)

Collapse
 
dechamp profile image
DeChamp

Been there before. Glad you shared it.