Adam
Adam

Reputation: 199

PHP json_decode: Object to Associative Array

The syntax for json_decode is:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

Note the 2nd parameter $assoc which is optional and defaults to false. When this parameter is true, json_decode converts objects to associative arrays.

My question is: Is there every a case where you would NOT want to convert a returned object into an associative array?

Upvotes: 2

Views: 3254

Answers (5)

amh15
amh15

Reputation: 305

If a function returns an associative array, prior to PHP 5.4 you couldn't access its members directly as foo()['xxx']. However if it returns an object you can access the members as foo()->xxx.

Of course you may also have libraries that require you to access the return value as an object.

Upvotes: 5

sfg2k
sfg2k

Reputation: 149

You need to pass an extra argument with true value. json_decode($p,true);

Upvotes: -3

KingCrunch
KingCrunch

Reputation: 131931

In my oppinion its a way to accentuate the difference between a list (in php expressed by a numeric array) and an entity (the object). This could be more readable, because one can read be the used accessor ([] or ->) what kind of data is accessed.

Upvotes: 0

dkamins
dkamins

Reputation: 21918

Personally I always ask for an associative array and find it easier to work with than the object returned when $assoc=false.

But I would say the majority of other people's code I've seen (largely various web service client libraries) has used json_decode with $assoc=false and objects instead of associative arrays. I think it's mostly a matter of preference though, as I've not seen any particular strong reason for choosing one way or the other.

Sorry for the non-answer :-)

Upvotes: 0

MeLight
MeLight

Reputation: 5575

When you want it converted to an object...

Upvotes: 2

Related Questions