How To Convert An Array To An Object In PHP?

Published October 31, 2024

Problem: Converting Arrays to Objects in PHP

Arrays and objects are key data structures in PHP. Developers often need to change an array into an object to handle data more easily or to meet certain coding needs. This process can be helpful when using APIs or organizing data in a structured way.

Methods to Convert an Array to an Object in PHP

Casting Method

You can convert an array to an object in PHP using casting. This method uses the (object) keyword to convert the array. Here's how:

$array = [
    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) $array;

This method only converts the top level of the array to an object. Nested arrays stay as arrays.

Tip: When to use casting

Use the casting method when you need a quick and simple conversion of a single-level array to an object. It's ideal for flat data structures where you don't need to convert nested arrays.

Standard Class Method

PHP's stdClass is an empty class for creating objects. Here's how to use it to convert an array to an object:

  1. Create a new stdClass object
  2. Loop through the array
  3. Assign each array element to the object

Here's the code:

$array = [
    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 = new stdClass();
foreach ($array as $key => $value) {
    $object->$key = $value;
}

This method lets you control the conversion process, allowing you to change the data during the loop.

Example: Modifying data during conversion

$object = new stdClass();
foreach ($array as $key => $value) {
    if (is_array($value)) {
        $object->$key = (object) $value; // Convert nested arrays to objects
    } else {
        $object->$key = strtoupper($value); // Convert string values to uppercase
    }
}

JSON Functions for Conversion

PHP's JSON functions offer another way to convert arrays to objects. This method has two steps:

  1. Use json_encode() to convert the array to a JSON string
  2. Use json_decode() to convert the JSON string to an object

Here's the code:

$array = [
    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 = json_decode(json_encode($array));

This method converts all nested arrays to objects, which is useful for complex data structures. However, it may be slower for large arrays.

Each of these methods has its strengths. Choose the one that fits your needs and coding style.