Somu Somu - 1 year ago 78
JSON Question

What happens when you pass a non-associative array to json_encode()?

My code is :

$arr = array();
echo '<br>';
echo json_encode($arr);

As you can see, I'm passing a non-associative array to
. The Output I get is

Array ( [0] => One [1] => Two [2] => Three )


What exactly is the second line of the output? If we pass an associative array to
, what is returned is a JSON Object, but this array that is returned is definitely does not look like a JSON object. So what is it?

Also, is there a way to convert a non-associative array to a JSON Object using

Answer Source

If you're trying to get it in proper object notation, try this:

echo json_encode($arr,JSON_FORCE_OBJECT);


{"0":"One", "1":"Two", "2":"Three"}

Refer to json_encode() options