Array2object and Object2array

Convert an associative array to an anonymous object and vice versa.

function array2object($array) {
 
    if (is_array($array)) {
        $obj = new StdClass();
 
        foreach ($array as $key => $val){
            $obj->$key = $val;
        }
    }
    else { $obj = $array; }
 
    return $obj;
}
 
function object2array($object) {
    if (is_object($object)) {
        foreach ($object as $key => $value) {
            $array[$key] = $value;
        }
    }
    else {
        $array = $object;
    }
    return $array;
}
 
 
// example:
 
$array = array('foo' => 'bar', 'one' => 'two', 'three' => 'four');
 
$obj = array2object($array);
 
print $obj->one; // output's "two"
 
$arr = object2array($obj);
 
print $arr['foo']; // output's bar
Snippet information

Author:
Someone of the Drupal developers

License:
GNU GPL

Language:
PHP

Created:
04/17/2006

Updated:
04/17/2006

Tags:
,




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

aaron s. hawley March 19, 2010 at 21:57
The PHP language's type casting rules do exactly this already.

http://www.php.net/manual/en/language.types.object.php
http://www.php.net/manual/en/language.types.array.php
Muzz March 18, 2010 at 06:31
Thanks a lot for this wonderful script. It helps me too too much. Actually i was working on soap and it returns values as Object, and one variable name of object was "iso-code", due to "-" i was unable to print the value, it was giving syntax error. And this script helps me so much.

Thanks a lot once again.
Alfredo December 04, 2007 at 17:58
I had to modify the object2array so it would go recursive and transform objects inside of an array into array as well, thought I would share

function object2array($object) {
if (is_object($object) || is_array($object)) {
foreach ($object as $key => $value) {
print "$key\r\n";
$array[$key] = $this->object2array($value);
}
}else {
$array = $object;
}
return $array;
}
Johny November 22, 2007 at 13:44
yes i have,
recursive call of the function array2object for multidimensional arrays

function array2object($arrGiven){
//create empty class
$objResult=new stdClass();

foreach ($arrLinklist as $key => $value){
//recursive call for multidimensional arrays
if(is_array($value)) $value=array2object($value);


$objResult->{$key}=$value;
}
return $objResult;
}