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);
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'
Which translates to an object in JavaScript:
{
"1": "blue",
"3": "brown"
}
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));
In PHP, $intersection
is restructured as an ordered/indexed array:
[0] => 'blue',
[1] => 'brown'
And when that's encoded (using json_encode
) for JavaScript's usage, it looks like:
['blue', 'brown']
Which is what I was expecting in the first place. 😀
Top comments (1)
Been there before. Glad you shared it.