See Arrays in RFC 8259 The JavaScript Object Notation (JSON) Data Interchange Format:
An array structure is represented as square brackets surrounding zero
or more values (or elements). Elements are separated by commas.array = begin-array [ value *( value-separator value ) ] end-array
You are observing this behaviour because your array is not sequential – it has keys 0
and 2
, but doesn’t have 1
as a key.
Just having numeric indexes isn’t enough. json_encode
will only encode your PHP array as a JSON array if your PHP array is sequential – that is, if its keys are 0, 1, 2, 3, …
You can reindex your array sequentially using the array_values
function to get the behaviour you want. For example, the code below works successfully in your use case:
echo json_encode(array_values($input)).