PHP convert array to object

July 14th 2012

Just had to write a little bit of code I thought I'd share with you.

I've found myself having to convert an array to object with PHP quite a lot recently, and I've been writing it from scratch every time. Well here it is. This little function converts an array to a stdClass object by looping through the values.

Check it out and let me know what you think in the comments.

PHP Code:
<?php
class Helper_ArrayToObject {

    public static function 
convert($array) {
        if(!
is_array($array)) {
            return 
$array;
        }

        
$obj = new stdClass();
        foreach (
$array as $key => $val) {
            if (
is_array($val)) {
                
$val self::convert($val);
            }

            
$obj->$key $val;
        }

        return 
$obj;
    }

}

Michael commented on Sep 15th 2012

Why not simply do $obj = (object)$myArray;

Arrays and Objects are easily type casted using PHP.

Roger commented on Oct 11th 2012

Because, run this code:

print("");
$array = array('name' => 'Joe', 'age' => '32', 'address' => array('123 My Street', 'Sometown', 'UK'));
var_dump((object)$array);
var_dump(Helper_ArrayToObject::convert($array));

My class iterates through child arrays to convert the entire array to an object. Don't type cast an array to an object unless you're 100% sure you don't need the sub arrays to remain arrays.