2nd Sep 2023
When JSON encoding an associative array, you have the following cases:
If at least one of the keys is non-numeric, you get a JSON object:
// Numeric keys: integers or integers in strings
json_encode([0 => 'zero', '1' => 'one']);
// -> ["zero","one"]
// At least one non-numeric key
json_encode([0 => 'zero', '1' => 'one', 'two' => 'two']);
// -> {"0":"zero","1":"one","two":"two"}
If the numeric keys are non-sequential (don’t start at 0, missing a step, or not assigned in ascending order), you get a JSON object:
// Keys sequential, start at 0, don't miss a step
json_encode(['0' => 'zero', '1' => 'one', '2' => 'two']);
// -> ["zero","one","two"]
// Keys don't start at 0
json_encode(['1' => 'one', 'two' => 'two']);
// -> {"1":"one","2":"two"}
// Keys miss a step
json_encode(['0' => 'zero', '2' => 'two']);
// -> {"0":"zero","2":"two"}
// Keys not in ascending order
json_encode(['1' => 'one', '0' => 'zero', '2' => 'two']);
// -> {"1":"one","0":"zero","2":"two"}