Return to Snippet

Revision: 44309
at April 9, 2011 18:38 by realpeterz


Initial Code
<?php
$person = array (
   'firstname' => 'Richard',
   'lastname' => 'Castera'
);
 
$p = (object) $person;
echo $p->firstname; // Will print 'Richard'
?>

<?php
function arrayToObject($array) {
    if(!is_array($array)) {
        return $array;
    }
    
    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}
?>

<?php
$person = array (
   'first' => array('name' => 'Richard')
);
 
$p = arrayToObject($person);
?>

<?php
// Now you can use $p like this:
echo $p->first->name; // Will print 'Richard'
?>

Initial URL
http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass

Initial Description


Initial Title
PHP - Convert Array to Object with stdClass

Initial Tags
php, object, array

Initial Language
PHP