|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2015-01-21 11:09 UTC] hamedwise at gmail dot com
Description:
------------
When using json_encode on an array, if the elements in the array are numbered from 1 to N, it generates objects are outputs, but when the elements are numbered from 0 to N, it generates an array as output.
The following code explains it:
echo json_encode(array(1=>"b",2=>"c"));
//Output: {"1":"b","2":"c"}
echo json_encode(array(0=>"a",1=>"b",2=>"c"));
//Output: ["a","b","c"]
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sat Oct 25 13:00:01 2025 UTC |
In the documentation, the sequential array is not numbered by the user. It goes like this: array("a","b","c"); but when the user defines the array as array(0=>"a",1=>"b",2=>"c"), it should put the indexes in the json_encode output, otherwise it would raise unexpected output mismatches.For PHP there is no difference between the following: array('a', 'b') array(0 => 'a', 1 => 'b') Anyhow, there is the JSON_FORCE_OBJECT option, so you can do json_encode(array(0 => 'a', 1 => 'b'), JSON_FORCE_OBJECT)