Is json_decode in PHP guaranteed to preserve ordering of elements when returning an array?

Wouldn't it make more sense in this case to use an array when you pass the JSON to PHP. If you don't have any object keys in the JSON (which become associative array keys in PHP), just send it as an array. That way you will be guaranteed they will be in the same order in PHP as in javascript.

json_decode('{["foo", "bar", "baz"]}');
json_decode('["foo", "bar", "baz"]'); //I think this would work

If you need associative arrays (which is why you are passing the second argument as true), you will have to come up with some way to maintain their order when passing. You will pry have to do some post-processing on the resulting array after you decode it to format it how you want it.

$json = '{[ {"key" : "val"}, {"key" : "val"} ]}';
json_decode($json, true);

Tags:

Php

Sorting

Json