PHP: How to convert an array to an object and vice versa

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

In PHP, arrays and objects are two fundamental types for storing data. Both have their unique features and use-cases. Understanding how to convert between arrays and objects is essential for developers to manipulate data effectively within their applications. This tutorial will guide you through the process of transforming arrays into objects and vice versa using various methods, accompanied by illustrative examples and scenarios.

Converting an Array to an Object

Converting an array to an object in PHP can be done using the (object) casting operator or the json_encode() and json_decode() functions. This conversion is useful when you want to utilize object syntax to access array elements or if a function specifically requires an object as a parameter.

Using Object Casting

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

$object = (object) $array;

// Accessing properties
echo $object->name;  // Outputs: John

Using JSON Functions

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

$json = json_encode($array);
$object = json_decode($json);

// Accessing properties
echo $object->name;  // Outputs: John

Using stdClass

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

$object = new stdClass();
foreach ($array as $key => $value) {
    $object->{$key} = $value;
}

// Accessing properties
echo $object->name;  // Outputs: John

Converting an Object to an Array

Objects can be converted to arrays using the (array) casting operator or the get_object_vars() function. This can be necessary when you want to work with array functions or require an associative array representation of an object’s properties.

Using Array Casting

$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$object->email = '[email protected]';

$array = (array) $object;

// Accessing values
echo $array['name'];  // Outputs: John

Using get_object_vars()

$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$object->email = '[email protected]';

$array = get_object_vars($object);

// Accessing values
echo $array['name'];  // Outputs: John

Advanced Examples

In more complex scenarios, objects and arrays may contain nested structures. Converting such data may require a recursive approach to ensure the integrity of the conversions.

Recursive Conversion from Array to Object

function arrayToObjectRecursive($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        $object->{$key} = is_array($value) ? arrayToObjectRecursive($value) : $value;
    }
    return $object;
}

$nestedArray = array(
    'name' => 'John',
    'age' => 30,
    'contacts' => array(
        'email' => '[email protected]',
        'phone' => '1234567890'
    )
);

$nestedObject = arrayToObjectRecursive($nestedArray);

Recursive Conversion from Object to Array

function objectToArrayRecursive($object) {
    $array = is_object($object) ? get_object_vars($object) : $object;
    foreach ($array as $key => $value) {
        $array[$key] = (is_array($value) || is_object($value)) ? objectToArrayRecursive($value) : $value;
    }
    return $array;
}

$nestedObject = new stdClass();
$nestedObject->name = 'John';
$nestedObject->age = 30;
$nestedObject->contacts = new stdClass();
$nestedObject->contacts->email = '[email protected]';
$nestedObject->contacts->phone = '1234567890';

$nestedArray = objectToArrayRecursive($nestedObject);

Handling Special Cases

Objects that implement the ArrayAccess interface behave like arrays but are objects underneath. Certain functions may require explicit conversion depending on their interface expectations.

ArrayAccess Objects

class ArrayObjectExample implements ArrayAccess {
    private $container = array();
    // ArrayAccess methods implementation
    // ...
}

$obj = new ArrayObjectExample();
// Add some data to the object
$obj['name'] = 'John';

// Convert to an array
$array = iterator_to_array($obj);

Conclusion

This tutorial walked you through different techniques to convert arrays to objects and objects to arrays in PHP. Whether you choose the simplicity of casting, the flexibility of JSON functions, or require advanced recursion, PHP offers versatile methods for data structure manipulation. Keep these tools at hand to seamlessly adapt your data to the needs of your application.