Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress How to Build a WordPress Plugin Connecting WordPress Plugins with 3rd Party APIs Parsing JSON with PHP: Part 2

Lewis Cowles
Lewis Cowles
74,902 Points

Your usage of {'varname'} to access json vars

So I must've skipped over how you access the JSON in this because one of my Juniors just showed me, and I was not impressed... Sure PHP can allow you to access invalid object names using object syntax, but surely array syntax would be simpler if you know the developer did not follow, what are standard variable declaration rules. I would say its better to deal with JSON using array rather than use this syntax, but I dont see accessing as array covered... Is there a reason for this?

1 Answer

By default, json_decode() will return an stdClass object from a JSON string. Since with JSON we are dealing with objects, it makes sense to return an object within PHP as well. If you want any array just add an extra boolean flag to the json_decode function and it will return an associative array:

json_decode($json_str, TRUE); 
Lewis Cowles
Lewis Cowles
74,902 Points

Hi Miguel, looks like we agree? (so a bit confusing), but I was advocating using 'true' and therefore returning an array. (note 'true' lowercase is what is being advocated by php-fig), I just happen to use it but it does make more sense as even modern C compilers use the lowercase true nowdays.

Thanks for the backup though