To convert an array into the object, stdClass() is used. The stdClass() is an empty class, which is used to cast other types to object. If an object is converted to object, its not modified. But, if object type is converted/type-casted an instance of stdClass is created, if it is not NULL. If it is NULL, the new instance will be empty.
Example 1: It converts an array into object using stdClass.Â
PHP
<?phpÂ
// Function to convert array into // stdClass objectfunction ToObject($Array) {         // Create new stdClass object    $object = new stdClass();         // Use loop to convert array into    // stdClass object    foreach ($Array as $key => $value) {        if (is_array($value)) {            $value = ToObject($value);        }        $object->$key = $value;    }    return $object;}Â
// Declare an array and initialize it$Original = array (    '1' => array(        'sNo' => '1',        'Age' => '20',        'name' => 'A'    ),    '2' => array(        'sNo' => '2',         'Age' => '21',         'name' => 'B'    ),    '3' => array(        'sNo' => '3',         'Age' => '22',         'name' => 'C'    ),    '4' => array(        'sNo' => '4',         'Age' => '23',         'name' => 'D'    ),    '5' => array(        'sNo' => '5',         'Age' => '24',         'name' => 'E'    ));Â
// Display the original arrayprint_r($Original);Â
// Function call$convertedObj = ToObject($Original);Â
// Display the stdClass objectprint_r($convertedObj);Â
?> |
Array
(
[1] => Array
(
[sNo] => 1
[Age] => 20
[name] => A
)
[2] => Array
(
[sNo] => 2
[Age] => 21
[name] => B
)
[3] => Array
(
[sNo] => 3
[Age] => 22
[name] => C
)
[4] => Array
(
[sNo] => 4
[Age] => 23
[name] => D
)
[5] => Array
(
[sNo] => 5
[Age] => 24
[name] => E
)
)
stdClass Object
(
[1] => stdClass Object
(
[sNo] => 1
[Age] => 20
[name] => A
)
[2] => stdClass Object
(
[sNo] => 2
[Age] => 21
[name] => B
)
[3] => stdClass Object
(
[sNo] => 3
[Age] => 22
[name] => C
)
[4] => stdClass Object
(
[sNo] => 4
[Age] => 23
[name] => D
)
[5] => stdClass Object
(
[sNo] => 5
[Age] => 24
[name] => E
)
)
Â
Example 2: It converts an array into object using stdClass.Â
PHP
<?phpÂ
// Function to convert array into// stdClass objectfunction ToObject($Array) {         // Create new stdClass object    $object = new stdClass();         // Use loop to convert array into object    foreach ($Array as $key => $value) {        if (is_array($value)) {            $value = ToObject($value);        }        $object->$key = $value;    }    return $object;}Â
// Declare an array$Original = array(1, 2, 3, 4, 5, 6);Â
// Display the array elementprint_r($Original);Â
// Function call to convert object$convertedObj = ToObject($Original);Â
// Display the stdClass objectprint_r($convertedObj);Â
?> |
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
stdClass Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
Â
