Array conversion with json_encode PHP

2

Oops, does anyone know why when I do this:

json_encode(array("0" => 0));

Return this: [0]

Instead: {"0":0}

    
asked by anonymous 14.07.2015 / 00:52

1 answer

6

PHP automatically detects if you are using numeric keys and converts to an array.

If you really want an object you can use JSON_FORCE_OBJECT in the second argument (PHP 5.3+), optional json_encode . (example: link )

Note that if you add another element to this array, without numeric key, json_encode already reads as an object.

Example ( link ):

echo json_encode(array("0" => 0, "foo" => "bar"));
// dá:
{"0":0,"foo":"bar"}
    
14.07.2015 / 01:09