PHP_Logo

Convert an array to an object in PHP

What?

The function introduced below alows you to recursively convert an array to an object.

See also: Convert an object to an array in PHP

The code

function array_to_object($variable){
    if (is_array($variable)){
        $object = new StdClass();
        foreach ($variable as $key=>$value){
            $object->$key = array_to_object($value);
        }
        return $object;
    } else{
        return $variable;
    }
}

One thought on “Convert an array to an object in PHP

Leave a Comment