Search code examples
phparraysjsonencode

Force json_encode() to produce object syntax instead of array syntax


I have an simple array:

array
  0 => string 'Kum' (length=3)
  1 => string 'Kumpel' (length=6)

when I encode the array using json_encode(), i get following:

["Kum","Kumpel"] 

My question is, what is the reason to get ["Kum","Kumpel"] instead of { "0" : "Kum", "1" : "Kumpel" }?


Solution

  • "{}" brackets specify an object and "[]" are used for arrays according to JSON specification. Arrays don't have enumeration, if you look at it from memory allocation perspective. It's just data followed by more data, objects from other hand have properties with names and the data is assigned to the properties, therefore to encode such object you must also pass the correct property names. But for array you don't need to specify the indexes, because they always will be 0..n, where n is the length of the array - 1, the only thing that matters is the order of data.

    $array = array("a","b","c");
    json_encode($array); // ["a","b","c"]
    json_encode($array, JSON_FORCE_OBJECT); // {"0":"a", "1":"b","2":"c"}
    

    The reason why JSON_FORCE_OBJECT foces it to use "0,1,2" is because to assign data to obeject you must assign it to a property, since no property names are given by developer (only the data) the encoder uses array indexes as property names, because those are the only names which would make sense.

    Note: according to PHP manual the options parameters are only available from PHP 5.3.

    For older PHP versions refer to chelmertz's answer for a way to make json_encode to use indexes.