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.
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->{}[];
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:
$datais an array with numeric keys128and129.- Each value is another array containing a
statuskey. (object) $datacreates astdClassobject for the outer array.$object->{129}gets the value stored under the numeric property name129.- That value is still an array, so
['status']retrieves its status text. - The script prints
Second message.
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
stdClassfor 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.
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'];
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:
Comparisons
| Situation | Best fit | Access example |
|---|---|---|
| Named, lightweight fields | stdClass object | $user->name |
| Ordered list or ID-indexed records | Array | $posts[129] |
| Nested decoded JSON as objects | json_decode($json) | $data->user->name |
| Nested decoded JSON as arrays | json_decode($json, true) | $data['user']['name'] |
| Data with validation and methods | Custom class | $post->publish() |
Shallow cast vs recursive conversion
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) $arraycreates astdClassobject.- The conversion is shallow; nested arrays are unchanged.
- Use
->propertyfor ordinary string keys such asname. - 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.
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
- Store at least two status records in an array indexed by numeric IDs.
- Create a function that accepts the records array and an integer ID.
- Return the selected record as an object when it exists.
- Return
nullwhen the requested ID does not exist. - Display the status for an existing ID and a clear message for a missing ID.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
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.