Skip to content

Instantly share code, notes, and snippets.

@ubermuda
Created October 22, 2012 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ubermuda/3931994 to your computer and use it in GitHub Desktop.
Save ubermuda/3931994 to your computer and use it in GitHub Desktop.
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"]"
@jubianchi
Copy link

Fuck +1

@mablae
Copy link

mablae commented Oct 22, 2012

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

@wouterj
Copy link

wouterj commented Oct 22, 2012

@mablae 👍

@ubermuda
Copy link
Author

@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 http://fr2.php.net/manual/en/function.json-encode.php, but that's still a bit weird :)

@dcousineau
Copy link

ಠ_ಠ ~ » 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.

@dcousineau
Copy link

See http://php.net/manual/en/function.json-decode.php for more information on the behavior of PHP's json_decode() function

@igorw
Copy link

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