Question

Convert a PHP Object to an Associative Array

phparrays

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 ->property and ['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.

Take Quiz

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('objectToArray', $value);
    }

    return $value;
}

Example:

$data = new stdClass();
$data->user = new stdClass();
$data->user->name = 'Ava';
$data->user->email = 'ava@example.com';
$data->tags = ['php', 'api'];

$result = objectToArray($data);

print_r($result);

Output:

Array
(
    [user] => Array
        (
            [name] => Ava
            [email] => ava@example.com
        )

    [tags] => Array
        (
            [0] => php
            [1] => api
        )
)

JSON-based shortcut

Another common shortcut is:

$array = json_decode(json_encode($object), true);

This can work for API-style data, but it is usually less ideal than a recursive PHP function because it:

  • adds extra encoding/decoding work
  • may change some data types
  • is less explicit

Use it only when you understand the trade-offs.

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:

  1. objectToArray($item) is called.
  2. $item is an object, so get_object_vars($item) turns it into:
[
    'title' => 'Book',
    'details' => <object>
]
  1. The value is now an array, so array_map('objectToArray', $value) runs the function on each element.
  2. For 'title', the value is 'Book'. It is not an object or array, so it is returned unchanged.
  3. For 'details', the value is an object. The function converts it into:
[
    'price' => 19.99,
    'inStock' => true
]
  1. Those inner values are checked too. Since 19.99 and true are scalar values, they are returned unchanged.
  2. The final result becomes:
[
    'title' => 'Book',
    'details' => [
        'price' => 19.99,
        'inStock' => true
    ]
]

This is the key idea of recursion: convert the current level, then repeat the same logic for each nested value.

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.

Take Quiz

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:

if (!is_object($response) && !is_array($response)) {
    return [];
}

Selective conversion

Sometimes only part of the response is converted:

$user = objectToArray($response->user);

Keeping data as objects when useful

Modern codebases sometimes prefer objects for stronger structure and arrays for flexible processing. Good developers convert only when there is a clear reason.

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

$array = json_decode(json_encode($object), true);

This shortcut may be convenient, but it is not always the best choice. Prefer a direct recursive function when you want clearer behavior.

4. Forgetting arrays can contain objects

A response may contain an array of objects:

$data->users = [$user1, $user2];

A good recursive function must handle both arrays and objects.

5. Expecting private or protected properties from any object

get_object_vars() only returns accessible properties in the current scope. For many API response objects like stdClass, this is fine. For custom class instances, behavior may differ.

6. Converting when you do not need to

If your code can work directly with objects, conversion may add unnecessary complexity. Convert only when it helps.

Comparisons

ApproachBest forHandles nested objectsNotes
(array) $objectSimple flat objectsNoFast and easy, top-level only
Recursive functionReal API data, nested structuresYesBest general-purpose solution
json_decode(json_encode($object), true)Quick data reshapingUsually yesLess explicit, extra overhead

Object access vs array access

StructureAccess syntaxExample
Object->$user->name
Associative array[]$user['name']

When to keep objects instead

Use objects whenUse arrays when
Data comes from typed models or domain classesYou need flexible key-based processing
You want methods and structureYou rely on array helper functions
Your codebase already uses object accessYour codebase already expects associative arrays
Take Quiz

Cheat Sheet

Quick conversions

$array = (array) $object;
  • Converts only the top level
  • Good for flat stdClass objects
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);
  • Quick but less ideal
  • Can add overhead and hide type changes

Rules to remember

  • Objects use ->
  • Arrays use []
  • (array) is not recursive
  • Recursive conversion should handle both objects and arrays
  • get_object_vars() works well for accessible object properties

Common checks

is_object($value)
is_array($value)
get_object_vars($object)

Typical result

$object->name      // before
$array['name']     // after

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.

Take Quiz

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

  1. Create a sample API response using stdClass with nested objects.
  2. Include at least one array inside the object.
  3. Write a recursive objectToArray() function.
  4. Convert the response and print the final array.
  5. Access at least one nested value using array syntax after conversion.
Take Quiz

Keep learning

Related questions

View more