Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

arrays

php

My code is :

<?php 
    $arr = array();
    array_push($arr,"One","Two","Three");
    print_r($arr);
    echo '<br>';
    echo json_encode($arr);
?>

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

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

What exactly is the second line of the output? If we pass an associative array to json_encode(), 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 json_encode()?

like image 942
Somu Avatar asked Sep 07 '25 23:09

Somu


1 Answers

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

echo json_encode($arr,JSON_FORCE_OBJECT);

Output:

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

Refer to json_encode() options

like image 89
Object Manipulator Avatar answered Sep 09 '25 13:09

Object Manipulator