2

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?

1
  • I would add custom methods to allow serialisation and deserialisation (like the Serializable interface) for json. This allows proper construction of objects from json and json from objects. Commented Jun 6, 2011 at 19:28

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

While this is no longer true, it was when the question was posted (and when json_decode() was written) so it's a good explanation for the default value.
2

When you want it converted to an object...

Comments

0

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 :-)

Comments

0

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.

Comments

-3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.