PHP How to Convert Object to Array Easily
(array)$object to cast it or get_object_vars($object) to get its properties as an array.Examples
How to Think About It
Algorithm
Code
<?php $obj = new stdClass(); $obj->name = "John"; $obj->age = 30; // Method 1: Casting $array1 = (array)$obj; print_r($array1); // Method 2: get_object_vars $array2 = get_object_vars($obj); print_r($array2); ?>
Dry Run
Let's trace converting an object with properties name='John' and age=30 to an array.
Create object
Object has properties: name='John', age=30
Cast object to array
Resulting array: ['name' => 'John', 'age' => 30]
Use get_object_vars
Returns array: ['name' => 'John', 'age' => 30]
| Step | Action | Result |
|---|---|---|
| 1 | Create object | {name: 'John', age: 30} |
| 2 | Cast to array | ['name' => 'John', 'age' => 30] |
| 3 | get_object_vars | ['name' => 'John', 'age' => 30] |
Why This Works
Step 1: Casting object to array
Using (array)$object converts the object properties into an associative array with keys as property names.
Step 2: Using get_object_vars function
The get_object_vars() function returns an associative array of accessible properties of the object.
Alternative Approaches
<?php $obj = new stdClass(); $obj->name = "John"; $obj->age = 30; $array = json_decode(json_encode($obj), true); print_r($array); ?>
Complexity: O(n) time, O(n) space
Time Complexity
Converting an object to an array requires visiting each property once, so it takes linear time relative to the number of properties.
Space Complexity
A new array is created to hold the properties, so space usage grows linearly with the number of properties.
Which Approach is Fastest?
Casting with (array) is fastest and simplest; get_object_vars() is similar; JSON encode/decode is slower but handles nested objects better.
| Approach | Time | Space | Best For |
|---|---|---|---|
| (array) cast | O(n) | O(n) | Simple, shallow objects |
| get_object_vars() | O(n) | O(n) | Accessible properties only |
| json encode/decode | O(n) | O(n) | Nested objects, deep conversion |
(array)$object for a quick and simple object to array conversion in PHP.