Question
I am integrating an API into my PHP website. The API returns data as objects, but the rest of my code works with associative arrays.
I would like a simple and practical way to convert a PHP object into an associative array.
For example, if I have an object returned from an API response, how can I turn it into an array that I can use with my existing array-based code?
Short Answer
By the end of this page, you will understand how to convert PHP objects into associative arrays, when a simple cast is enough, when you need a recursive solution, and what common pitfalls to watch for when working with nested API response data.
Concept
In PHP, objects and associative arrays are different data structures.
- An object stores data in properties and is accessed with
-> - An associative array stores data as key-value pairs and is accessed with
[]
Example:
$userObject->name;
$userArray['name'];
When you integrate with APIs, libraries, or database tools, you may receive data as objects. But your own code may expect arrays. In that case, you often need to convert one structure into the other.
A quick conversion can be done with a cast:
$array = (array) $object;
This works well for simple, flat objects. However, many API responses contain nested objects and arrays. A plain cast only converts the top level. Inner objects remain objects.
That is why developers often use a recursive conversion function when handling real API data.
This matters because:
- it helps your code use a consistent data format
- it makes array functions easier to use
- it reduces confusion when mixing
->propertyand['key'] - it helps when passing data into older array-based code
In short, object-to-array conversion is really about data shape compatibility.
Mental Model
Think of an object and an associative array as two different styles of labeled storage.
- An object is like a cabinet with named drawers you open using
-> - An associative array is like a dictionary where you look up values by key using
[]
Both can hold similar information, but you interact with them differently.
A simple cast is like putting labels from the cabinet onto a sheet of paper. That works for the outer level. But if a drawer contains another cabinet, you still need to open that inner cabinet and copy its labels too. That is what recursive conversion does.
Syntax and Examples
Basic cast
For a simple object:
$person = new stdClass();
$person->name = 'Ava';
$person->age = 28;
$array = (array) $person;
print_r($array);
Output:
Array
(
[name] => Ava
[age] => 28
)
This is the fastest and simplest option for a flat object.
Recursive conversion for nested data
If the object contains nested objects, use a recursive function:
function objectToArray($value) {
if (is_object($value)) {
$value = get_object_vars($value);
}
if (is_array($value)) {
return array_map(, );
}
;
}
Step by Step Execution
Consider this example:
function objectToArray($value) {
if (is_object($value)) {
$value = get_object_vars($value);
}
if (is_array($value)) {
return array_map('objectToArray', $value);
}
return $value;
}
$item = new stdClass();
$item->title = 'Book';
$item->details = new stdClass();
$item->details->price = 19.99;
$item->details->inStock = true;
$result = objectToArray($item);
print_r($result);
What happens step by step:
objectToArray($item)is called.
Real World Use Cases
Object-to-array conversion is common in real PHP projects.
API responses
Many APIs return decoded JSON as objects. If your application expects arrays, conversion helps standardize the format.
$response = json_decode($json); // object
$data = objectToArray($response); // array
Legacy code integration
Older PHP codebases often use arrays heavily. If a newer library returns objects, converting data may be the easiest compatibility step.
Templating or view rendering
Some templates or helper functions may expect array input:
renderCard($userArray);
Data transformation pipelines
Arrays are often easier to process with functions like:
array_map()array_filter()array_keys()array_column()
Logging and debugging
Sometimes developers convert objects to arrays so they can inspect the structure more easily during debugging.
Real Codebase Usage
In real projects, developers usually do not convert everything blindly. They choose a pattern based on where the data enters the system.
Common pattern: convert at the boundary
When data comes from an API, convert it once near the API client instead of repeatedly throughout the app.
function fetchUserData(): array {
$json = file_get_contents('https://example.com/api/user');
$object = json_decode($json);
return objectToArray($object);
}
This keeps the rest of the code consistent.
Validation after conversion
After converting, developers often validate required keys:
$data = objectToArray($response);
if (!isset($data['user'])) {
throw new RuntimeException('Missing user data');
}
Guard clauses
A guard clause can avoid errors early:
Common Mistakes
1. Assuming (array) converts nested objects too
Broken expectation:
$data = new stdClass();
$data->user = new stdClass();
$data->user->name = 'Ava';
$result = (array) $data;
print_r($result);
Many beginners expect user to become an array too. It does not. Only the top level is cast.
Use recursion for nested data.
2. Mixing object and array syntax
Broken code:
$data = objectToArray($response);
echo $data->user;
After conversion, use array syntax:
echo $data['user'];
3. Using JSON conversion without understanding side effects
Comparisons
| Approach | Best for | Handles nested objects | Notes |
|---|---|---|---|
(array) $object | Simple flat objects | No | Fast and easy, top-level only |
| Recursive function | Real API data, nested structures | Yes | Best general-purpose solution |
json_decode(json_encode($object), true) | Quick data reshaping | Usually yes | Less explicit, extra overhead |
Object access vs array access
| Structure | Access syntax | Example |
|---|---|---|
| Object | -> |
Cheat Sheet
Quick conversions
$array = (array) $object;
- Converts only the top level
- Good for flat
stdClassobjects
function objectToArray($value) {
if (is_object($value)) {
$value = get_object_vars($value);
}
if (is_array($value)) {
return array_map('objectToArray', $value);
}
return $value;
}
- Converts nested objects and arrays recursively
- Best for API response data
JSON shortcut
$array = json_decode(json_encode($object), true);
FAQ
How do I convert a PHP object to an associative array?
For a simple object, use:
$array = (array) $object;
For nested objects, use a recursive function.
Does casting with (array) convert nested objects too?
No. It converts only the top-level object. Inner objects remain objects.
What is the best way to convert API response objects in PHP?
A recursive function is usually the best choice because API responses often contain nested objects and arrays.
Can I use json_encode() and json_decode() to convert an object to an array?
Yes, this is a common shortcut:
$array = json_decode(json_encode($object), true);
But it is usually less clear and less efficient than a direct recursive conversion.
Why does my converted data still contain objects?
Because a plain cast like (array) $object only affects the outer object. Nested objects must be converted separately.
Should I always convert objects to arrays in PHP?
No. Convert only when your code or tools expect arrays. If objects work fine in your codebase, keeping them as objects may be better.
Mini Project
Description
Build a small PHP utility that accepts an API-style response object and converts it into an associative array. This demonstrates how to handle nested objects and arrays in a practical way before passing the data into existing array-based code.
Goal
Create a reusable objectToArray() helper and use it to convert and print nested API response data as a clean associative array.
Requirements
- Create a sample API response using
stdClasswith nested objects. - Include at least one array inside the object.
- Write a recursive
objectToArray()function. - Convert the response and print the final array.
- Access at least one nested value using array syntax after conversion.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.
Converting HTML and CSS to PDF in PHP: Core Concepts, Limits, and Practical Approaches
Learn how HTML-to-PDF conversion works in PHP, why CSS support varies, and how to choose practical approaches for reliable PDF output.