Working with JSON in PHP

Josh Sherman
1 min read
Software Development PHP

JSON is one of my favorite human readable formats. It’s widely used and has great support in PHP as well as other languages. PHP allows you to easily convert variables into JSON and JSON into objects or arrays. First, let’s take a look at how we can convert an array into JSON:

$array = ['var' => 'val', 3 => 14, [1,2,3]];
$json  = json_encode($array);

The resulting JSON would be:

{"var":"val","3":14,"4":[1,2,3]}

Converting back is just as easy and you can opt to work with a PHP object or an array by way of the second argument which defaults to object format:

$object = json_decode($json);
$array  = json_decode($json, true);

I prefer to work with an array because I feel the interface is a bit more natural than that of an object. It’s really up to you though, go with the format that you prefer to work with :)

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles