Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ash:~$ php -r 'var_dump(json_encode([1 => "foo"]));'
string(11) "{"1":"foo"}"
ash:~$ php -r 'var_dump(json_encode([0 => "foo"]));'
string(7) "["foo"]"

Fuck +1

mablae commented Oct 22, 2012

php -r 'var_dump(json_encode([0 => "foo"], JSON_FORCE_OBJECT));'

wouterj commented Oct 22, 2012

@mablae 👍


ubermuda commented Oct 22, 2012

@mablae yes, but the real problem here is that feeding json_decode the result of json_encode will not necessarily yield the original value by default.

ash:~$ php -r 'var_dump(json_decode(json_encode([ 1 => "foo" ])));'
class stdClass#1 (1) {
  public $1 =>
  string(3) "foo"

I understand there are technical reasons for that, and also that it is documented at, but that's still a bit weird :)

ಠ_ಠ ~ » php -r 'var_dump(json_decode(json_encode(array( "foo" ))));'
array(1) {
  [0] =>
  string(3) "foo"
ಠ_ಠ ~ » php -r 'var_dump(json_decode(json_encode(array( 1 => "foo" )), true));'
array(1) {
  [1] =>
  string(3) "foo"

It still makes perfect sense. Remember JavaScript has 2 distinct primitive data types Array and Object. PHP also has Array and Object data types, however many people do not use stdClass given that PHP doesn't have "real" arrays, we only have hashmaps which feel more like JavaScript objects in practice.

The decode process is literal unless you force it to always use hashmaps. In the example you provided the output of json_encode was {"1":"foo"} (an object) which json_decode translated literally into an object. If you pass in the results of json_encode(["foo"]); you get an array out because ["foo"] is literally an array.

See for more information on the behavior of PHP's json_decode() function

igorw commented Oct 22, 2012

If you want to force an object in a nested structure, you can use ArrayObject:

$ php -r 'var_dump(json_encode([new ArrayObject([0 => "foo"])]));'
string(13) "[{"0":"foo"}]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment