🍿 Force empty PHP array to become JSON object
Snacks (🍿) are my collection of recipes for solving problems. Often recorded (and cleaned up) from actual discussions where I'm involved in helping others with technical problems. Not all solutions are mine but I started collecting them in one place because you never know when you need one.
As I've written in My love-hate relationship with PHP Arrays, the way PHP's way to deal with arrays is a bit annoying when having to deal with JSON interoperability. If you're not careful, you might end up with array when you thought you got an object or vice versa.
One edge case that I didn't touch on 6 years ago but came to wrestle today was how to deal with empty arrays as objects.
If you have an associative PHP array like:
$book = [ "author" => "Douglas Adams", "name" => "Hitchhiker's Guide to the Galaxy"];
and you return it as JSON via an API (converting with json_encode
), you end up with
{
"author": "Douglas Adams",
"name": "Hitchhiker's Guide to the Galaxy"
}
but if there's no data for a given book when you fetch the data somewhere and you end up with
$book = [];
you end up with JSON as:
[]
So you get an object when there's data and array when there's not. That's not great.
The way to convert an empty array into JSON object is to cast it into PHP object:
$book = (object)$book;
in which case the empty one will become an empty object in JSON:
{}