Array conversion with json_encode PHP

Asked

Viewed 291 times

2

Whoa, somebody knows why when I do this:

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

Return that: [0]

Instead: {"0":0}

1 answer

6


PHP automatically detects whether 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: https://ideone.com/kFftSu)

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

Example (https://ideone.com/yyrya4):

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.