How to convert stdClass object to Array in PHP
In this exercise, you will learn how to convert stdclass object to array using PHP.
The stdClass is the empty class in PHP which is used to cast other types to an object. The stdClass is not the base class of the objects. If an object is converted to an object, it is not modified. But, if an 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. An array is a collection of key/value pairs. In programming, sometime we need to convert stdclass objects to arrays. It is easy to convert stdclass object to array if both the arrays and objects are one-dimensional, but it might be a little tricky if using multidimensional arrays and objects.
Convert stdClass objects to array
PHP provides stdClass as a generic empty class which is useful for adding properties dynamically and casting. It is useful in dynamic objects. Suppose we have the following stdClass objects.
#define stdObjects to store employee details $obj = new stdClass; $obj->name = "Priska"; $obj->position = "Data Administrator" $obj->age = 26; $obj->experience = 3;The following PHP code converts the above defined objects into an array.
Output of the above code:
Array ( [name] => Priska [position] => Data Administrator [age] => 26 [experience] => 3 )Function to Convert stdClass Objects to Multidimensional Arrays
In the given example, we have converted the stdClass objects to multidimensional arrays.
Output of the above code:
need an explanation for this answer? contact us directly to get an explanation for this answerArray ( [name] => Priska [position] => Data Administrator [age] => 26 [experience] => 3 [address] => Array ( [houseno] => K-92 A, Bank Street [location] => Southcamp [city] => Banglore ) )