In this episode, we take a look at a super quick and handy way to convert an array into an object in PHP. We start by creating a simple array structure that actually has an array nested inside of it, just to make sure we're covering more than just a flat list. For example, we use an array with an items
key, and inside that, we have another array containing things like "milk", "eggs", and "bread".
Next, we go through what this array looks like when you print it out, so you get a feel for the data format. From there, we jump into the conversion process using PHP’s built-in json_encode
and json_decode
functions. First, we encode the array, turning it into a JSON string, and take a quick look at the output. Then, we decode the JSON string back, but here’s the crucial part: if we don’t pass true
as the second argument to json_decode
, PHP will turn that JSON into an object rather than an associative array.
We verify that the structure is now an object, and even show you how you can iterate over the object's properties to access and work with the data inside. It's a neat trick that comes in handy when you want quick object-like access to your data without having to write a bunch of boilerplate code.
So, if you ever need to quickly convert an array to an object in PHP, this episode shows you exactly how to do it with just a couple of lines!