This article demonstrates how to convert an object to an array in PHP.

1. Using Type Casting

A simple option to convert an object to an associative array is typecasting. To cast an object to an array, you can simply write the array type within parentheses before the object to convert. When a PHP object is converted to an associative array, all the object properties become the array elements. For example, the following solution casts a StdClass object to an array:

Download  Run Code

 
The following solution typecasts an object having only public properties.

Download  Run Code

 
As evident from the above examples, type casting works well with StdClass and class for all public properties. If your object contains any non-public fields, the array keys will include the visibility scope. The private and protected properties will have the class name and '*' prepended to the element name, respectively. Note that the class name and '*' are separated by the null character ("\0") on both sides, as illustrated below:

Download  Run Code

2. Using get_object_vars() function

Alternatively, you may use the get_object_vars() function to get an associative array of accessible non-static properties of the specified object according to scope. Note that the private and protected properties in the object will be ignored, if this function is called from within the scope of the object.

Download  Run Code

3. Using Reflection

You may use Reflection to access private and protected fields outside the object’s scope. This example uses ReflectionClass::getProperties() to retrieve reflected properties and stores them in an array. Unlike type casting, this solution results in proper key names for non-public fields. Before PHP 8.1.0, you must call ReflectionProperty::setAccessible() to enable access to a protected or private property. As of PHP 8.1.0, all properties are accessible by default.

Download  Run Code

4. Using json_encode() and json_decode() function

If your object only has public attributes, you can serialize it to JSON and then deserialize it. You can convert the object into a string containing the JSON representation with json_encode(), and then convert the JSON string into an associative array using the json_decode() function with its second parameter set to true.

Download  Run Code

 
Since json_encode() function is recursive, an object will be serialized recursively. For example,

Download  Run Code

5. Using foreach loop

Finally, you can write a recursive procedure to convert an object to a multidimensional array using a foreach loop, as shown below. This option is available for objects with all public properties. Any private and protected properties in the object won’t be converted.

Download  Run Code

That’s all about converting an object to an array in PHP.