PHP Convert Array to Object

Just a quick one today, I’ve seen a few people asking how to convert an array to an object in PHP. All the responses to these questions seem to involve creating a recursive function to loop through the array and create corresponding properties in a stdClass for each key in the array.

There happens to be a MUCH simpler way built in to PHP from version 5.2, all you need to do is this:

$object = json_decode(json_encode($array));

This works because when you encode an array using JSON in PHP, non-numeric keys become object properties, so when the JSON string is convered back to an object, the new properties remain instead of being turned back into array keys.

Give it a try, it works perfectly.

- MB

Posted in: Programming by Matt Bearman on 27th April 2011 at 11:41 pm
Tags: , , , ,

No Responses to “PHP Convert Array to Object” - (Leave a comment)

No comments yet.

RSS | TrackBack URL

Leave a comment