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

PHP

What is the difference between json_encode() and json_decode?

I'm not sure if I'm understanding these two functions right in PHP can someone explain it to me? I think json_encode makes sure that php can read the .json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name. I might be wrong.

2 Answers

Hi Kevin!

json_encode converts PHP values/objects/arrays into JSON objects/strings

json_decode converts JSON objects/strings into PHP values/objects/arrays

It gets used a lot in scenarios where you are sending HTTP request and response data (in AJAX operations, for example).

It is something you should experiment with to really understand.

Go back and forth and examine your output (especially when you log data to the console).

More info:

https://www.w3schools.com/php/php_ref_json.asp

https://www.bitdegree.org/learn/php-json-decode

https://www.youtube.com/watch?v=iqNiINZ4Sxg

http://www.mustbebuilt.co.uk/php/php-and-json-json_encode-and-json_decode/

https://www.w3schools.in/json/json-php/

I hope that helps.

Stay safe and happy coding!

Thank you Peter. A very clear explanation and to the point. I hope you stay save too!