Convert Array to Object in PHP
When you need to convert an Array to Object in PHP there is a quick way to do this:
[code="php"]
$array = (
'foo' => 'foo',
'bar' => 'bar'
);
$object = (object) $array();?>
[/code]
This snippet of code covert the array to object, but not recursively. You can get more info on PHP Objects page.
You can easily convert an array to an object recursively if you check the variable type and build the object with the help of variable variables:
[code="php"]
function array_to_object($array) {
$object = new stdClass();
foreach($array as $key => $value) {
$object->$key = is_array($value) ? array_to_object($value) : $value;
}
return $object;
}
$array = (
'foo' => 'foo',
'bar' => 'bar'
'arr' => array(
'foo' => 'foo'
'bar' => 'bar'
)
);
$object = array_to_object($array);?>
[/code]
So if you need to convert the array recursively you need to use the second method, else the first method is more reliable.


Tags: 



3 Responses
June 25, 2010 1
Very Good site, thank yo mister, it’s help’s me!
June 29, 2010 2
This is my first visit here, but I will be back soon, because I really like the way you are writing, it is so simple and honest
September 14, 2010 3
Thank’s for this nice tips
Leave a Reply