php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #68874 json_encode incorrect behaviour
Submitted: 2015-01-21 11:09 UTC Modified: 2015-03-19 21:16 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:1 (100.0%)
From: hamedwise at gmail dot com Assigned:
Status: Not a bug Package: json (PECL)
PHP Version: 5.5.20 OS: Windows 7 / CentOS 6
Private report: No CVE-ID: None
 [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"]


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2015-01-21 22:11 UTC] cmbecker69 at gmx dot de
That is sensible and well documented[1] behavior. IMO not a bug.

[1] <http://php.net/manual/en/function.json-encode.php#example-3898>
 [2015-01-22 06:30 UTC] hamedwise at gmail dot com
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.
 [2015-01-22 11:31 UTC] cmbecker69 at gmx dot de
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)
 [2015-03-19 21:16 UTC] cmb@php.net
-Status: Open +Status: Not a bug
 [2015-03-19 21:16 UTC] cmb@php.net
Thank you for taking the time to write to us, but this is not
a bug. Please double-check the documentation available at
http://www.php.net/manual/ and the instructions on how to report
a bug at http://bugs.php.net/how-to-report.php

See comments above.
 
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Fri Apr 19 12:01:25 2019 UTC