Convert multidimensional array to object – PHP

As you may already know, you can convert an array into an object simple like this:

 'John', 'last_name' => 'Doe');
    $object = (object) $array;
?>

Then you call the object:

first_name;
?>

The problem is that you can’t do this with multidimensional array. So, for this, i’ve found the solution:

 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object;
    }
    else {
      return FALSE;
    }
}

// Now we can test the method
$array = array(
    'f_name' => 'Rada',
    'l_name' => 'Calin',
    'age' => 26,
    'parents' => array(
        'mom' => array(
            'f_name' => 'Rada',
            'l_name' => 'Daniela',
            'age' => 45,
        ),
        'dad' => array(
            'f_name' => 'Rada',
            'l_name' => 'Ioan',
            'age' => 46,
        )
    )
);

// Convert the array to object
$user = arrayToObject($array);

// Example output
echo $user->parents->mom->l_name;
?>

Hope this is helpful 😉