Question

Convert an Array to an Object in PHP

phparraysobjectcasting

Question

How can I convert the following PHP array into an object?

$data = [
    128 => [
        'status' => "Figure A. Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.",
    ],
    129 => [
        'status' => 'The other day at work, I had some spare time',
    ],
];

I would like to access the converted data as object properties where appropriate.

Short Answer

You will learn how PHP converts arrays into stdClass objects, why a simple cast only converts one level, and how to recursively convert nested arrays when an object tree is needed.

Concept

In PHP, an array stores values using keys, while an object stores values in properties. The simplest way to convert an array to a generic PHP object is an object cast:

$object = (object) $array;

PHP creates an instance of stdClass, the built-in generic object type. Each array key becomes an object property when it is a valid property name.

A key detail is that casting is shallow: PHP converts only the outer array. Arrays contained inside it remain arrays. This matters for nested API responses, configuration data, and decoded data structures: decide whether you want only the top-level container to be an object or every nested level to become an object.

Also, numeric array keys are not convenient normal properties. You can inspect or access them using braces, such as $object->{128}, but an array is often the clearer structure when numeric keys represent IDs or list positions.

Mental Model

Think of an array as a filing cabinet:

  • Each drawer has a label (the key) and holds a value.
  • An object is a form with named fields (properties).

Casting an array to an object changes the outer filing cabinet into a form. However, if a drawer contains another filing cabinet, it stays a filing cabinet unless you explicitly convert it too.

For the example, the outer keys 128 and 129 are like numbered drawer labels. The values inside each drawer are smaller arrays with a status label.

Take Quiz

Syntax and Examples

Use (object) to create a generic stdClass object from an array.

<?php
$user = [
    'name' => 'Maya',
    'active' => true,
];

$userObject = (object) $user;

echo $userObject->name; // Maya

String keys become normal properties, so ['name' => 'Maya'] can be read as $userObject->name.

With the question's nested data:

<?php
$data = [
    128 => [
        'status' => "Figure A. Facebook's horizontal scrollbars showing up on a 1024x768 screen resolution.",
    ],
    129 => [
        'status' => 'The other day at work, I had some spare time',
    ],
];

$object = (object) $data;

// The outer array is now an object.
// The nested values are still arrays.
echo $object->{128}['status'];

The {128} syntax is required because 128 is a numeric key. The nested ['status'] remains array syntax because the nested value was not converted.

Step by Step Execution

Consider this code:

<?php
$data = [
    128 => ['status' => 'First message'],
    129 => ['status' => 'Second message'],
];

$object = (object) $data;

$message = $object->{129}['status'];
echo $message;

Step by step:

  1. $data is an array with numeric keys 128 and 129.
  2. Each value is another array containing a status key.
  3. (object) $data creates a stdClass object for the outer array.
  4. $object->{129} gets the value stored under the numeric property name 129.
  5. That value is still an array, so ['status'] retrieves its status text.
  6. The script prints Second message.

If the outer keys were names such as 'first' and 'second', access would be more readable:

$object->first['status'];

Real World Use Cases

Array-to-object conversion can be useful when data has named fields and property access makes code easier to read.

  • Application configuration: Convert settings such as ['timezone' => 'UTC'] to $settings->timezone.
  • API adapters: Normalize an array from a legacy library into an object expected by another part of the application.
  • Template data: Pass a small, named set of values to a view as an object.
  • Dynamic records: Use stdClass for lightweight data objects when creating a dedicated class would be unnecessary.

For collections indexed by IDs, such as the 128 and 129 keys in this question, keeping the outer structure as an array is frequently more practical. Arrays naturally represent ID-indexed lookups and support foreach, array_filter(), and other array functions.

Take Quiz

Real Codebase Usage

In production PHP code, developers usually choose the structure based on the data's meaning rather than converting everything automatically.

Use a small data object for named fields

<?php
$config = (object) [
    'host' => 'localhost',
    'port' => 3306,
];

if ($config->port < 1) {
    throw new InvalidArgumentException('Port must be positive.');
}

Keep ID-indexed records as an array

<?php
$postsById = [
    128 => ['status' => 'First message'],
    129 => ['status' => 'Second message'],
];

$postId = 129;

if (!isset($postsById[$postId])) {
    throw new RuntimeException('Post not found.');
}

echo $postsById[$postId]['status'];

Use a dedicated class when behavior matters

If the data needs validation, methods, or reliable types, create a class instead of relying on a generic stdClass.

<?php
final class Post
{
    public function __construct(
        public int $id,
        public string $status,
    ) {
    }
}

$post = new Post(129, 'Second message');
echo $post->status;

This makes the expected fields explicit and prevents accidental misspellings from silently creating dynamic properties.

Common Mistakes

Expecting nested arrays to become objects automatically

This is a shallow conversion:

$object = (object) [
    'user' => ['name' => 'Maya'],
];

// Incorrect: user is still an array.
echo $object->user->name;

Use array access for the nested value:

echo $object->user['name'];

Or recursively convert nested arrays if that is truly the desired structure.

Using -> directly with a numeric key

This is invalid PHP syntax:

// Incorrect
echo $object->128;

Use braces:

echo $object->{128};

Treating all keys as valid property names

Keys containing characters such as hyphens cannot be used with regular property syntax:

$object = (object) ['first-name' => 'Maya'];

// Incorrect: PHP reads this as subtraction.
// echo $object->first-name;

echo $object->{'first-name'};

Converting only to avoid bracket syntax

Do not convert an array merely because $data['status'] looks less appealing than $data->status. Arrays are often the correct choice, especially for lists and ID-indexed data.

Assuming a missing property is safe

Accessing a missing property can produce a warning. Check first when data may be incomplete:

if (property_exists($object, 'status')) {
    echo $object->status;
}

Comparisons

SituationBest fitAccess example
Named, lightweight fieldsstdClass object$user->name
Ordered list or ID-indexed recordsArray$posts[129]
Nested decoded JSON as objectsjson_decode($json)$data->user->name
Nested decoded JSON as arraysjson_decode($json, true)$data['user']['name']
Data with validation and methodsCustom class$post->publish()

Shallow cast vs recursive conversion

ApproachWhat it convertsUseful when
(object) $arrayOnly the outer arrayOnly top-level property access is needed
Recursive helperEvery nested arrayYou need a complete object tree
Custom classSelected values with defined typesThe data has business rules or behavior
Take Quiz

Cheat Sheet

// Convert the outer array to stdClass
$object = (object) $array;

// Named string key
$name = $object->name;

// Numeric or unusual key
$value = $object->{128};
$value = $object->{'first-name'};

// A nested array remains an array after a simple cast
$status = $object->{128}['status'];
  • (object) $array creates a stdClass object.
  • The conversion is shallow; nested arrays are unchanged.
  • Use ->property for ordinary string keys such as name.
  • Use ->{'key'} for numeric keys or keys with special characters.
  • Keep arrays for lists, numeric indexes, and data you want to process with array functions.
  • Prefer a custom class when the data requires validation, methods, or strict structure.

FAQ

Does (object) $array convert nested PHP arrays to objects?

No. It converts only the outer array. Any array values inside it remain arrays.

What type of object does PHP create when casting an array?

PHP creates an instance of stdClass, a generic object that can hold dynamic properties.

How do I access an object property with a numeric key in PHP?

Use curly braces: $object->{128}. Regular syntax such as $object->128 is invalid.

Should I convert an ID-indexed array to an object?

Usually no. Arrays are clearer for numeric IDs and work naturally with foreach and PHP array functions.

How can I convert a nested array recursively to objects?

Use a recursive function that converts each array value before casting the current array. This is appropriate only when all nested structures should be objects.

Is json_decode() an array-to-object conversion tool?

Not for an existing PHP array. It decodes JSON text. By default it returns objects for JSON objects; with true as its second argument, it returns associative arrays.

Can I use an object cast for a custom class?

No. (object) $array creates stdClass, not an instance of your own class. Instantiate and populate a custom class explicitly.

Take Quiz

Mini Project

Description

Build a small status lookup utility for records stored by numeric ID. It demonstrates why an ID-indexed outer structure can remain an array while each individual record can be converted into an object for readable named-field access.

Goal

Retrieve and display a status message for a supplied record ID, handling missing records safely.

Requirements

  1. Store at least two status records in an array indexed by numeric IDs.
  2. Create a function that accepts the records array and an integer ID.
  3. Return the selected record as an object when it exists.
  4. Return null when the requested ID does not exist.
  5. Display the status for an existing ID and a clear message for a missing ID.
Take Quiz

Keep learning

Related questions

View more