phparraysobjectjson

Why does the PHP function "json_decode" return an object?


The PHP function json_decode (by default) returns an object. Switching the second argument will return an array.

Maybe I just don't understand objects, but I thought objects have properties and methods (maybe events too). Arrays only have properties.

Given that json_decode will only ever return properties and never methods, shouldn't it always return an array?


Solution

  • It returns an object because JSON defines an object structure. This is what the 'O' stands for in 'JSON'.

    This is where the differences between languages starts to become more obvious.

    Javascript uses objects where PHP might use an array with named keys. JS can't have named keys in an array, only in an object. Other languages have other limitations to how they structure their variables.

    Using an object means that PHP is as consistent with other language implementations of JSON as possible. Since JSON is designed for cross-language communication, being consistent is important.

    But as you say, in PHP it is sometimes easier to work with an array, so this is why PHP offers the option of converting it directly to an array.

    But be aware that PHP arrays are not the same as JSON arrays and objects. PHP allows you to mix named and numbered array keys. This does not map well to JSON, so if you're using PHP arrays to work with JSON you have to be careful of it. If you're using PHP objects for your JSON work, then you won't have this mismatch in functionality.