Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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