How to convert an array into an object using stdClass()

Alexandrw picture Alexandrw · Oct 9, 2013 · Viewed 181.9k times · Source

I have made the following array:

$clasa = array(
        'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
        'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
        'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
        'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
        'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);

I would like to know how to convert this array into an object using stdClass(), I'm a PHP beginner, a simple example would be very helpful, I've tried searching for similar questions, but the answers are complicated and go beyond my understanding of basic classes and objects.

Answer

Ekramul Hoque picture Ekramul Hoque · Oct 9, 2013

You just add this code

$clasa = (object) array(
            'e1' => array('nume' => 'Nitu', 'prenume' => 'Andrei', 'sex' => 'm', 'varsta' => 23),
            'e2' => array('nume' => 'Nae', 'prenume' => 'Ionel', 'sex' => 'm', 'varsta' => 27),
            'e3' => array('nume' => 'Noman', 'prenume' => 'Alice', 'sex' => 'f', 'varsta' => 22),
            'e4' => array('nume' => 'Geangos', 'prenume' => 'Bogdan', 'sex' => 'm', 'varsta' => 23),
            'e5' => array('nume' => 'Vasile', 'prenume' => 'Mihai', 'sex' => 'm', 'varsta' => 25)
);

If you want to see is this stdClass object just call this

print_r($clasa);

If you want to convert an array to object code will be

$arr = array('a'=>'apple','b'=>'ball');
$arr = (object) $arr;

You don't need to use stdClass. It will automatically converted to stdClass