PHP

Converting PHP Arrays to Objects and Back

Learn efficient methods to transform PHP arrays into objects and objects back into arrays, useful for working with JSON data or dynamic data structures.

<?php
// 1. Array to Object
$dataArray = [
    'name' => 'John Doe',
    'age' => 30,
    'city' => 'New York'
];

$dataObject = (object) $dataArray;

echo "Array to Object:
";
print_r($dataObject);
echo "Object name: " . $dataObject->name . "

";

// 2. Object to Array
class User {
    public $name;
    public $email;
    public $status;

    public function __construct($name, $email, $status) {
        $this->name = $name;
        $this->email = $email;
        $this->status = $status;
    }
}

$userObject = new User('Jane Smith', '[email protected]', 'active');

// Method A: Type casting (only public properties)
$userArrayA = (array) $userObject;
echo "Object to Array (Type Casting):
";
print_r($userArrayA);

// Method B: Using json_encode/decode (all properties, including protected/private via serialization)
$userArrayB = json_decode(json_encode($userObject), true);
echo "
Object to Array (JSON Encode/Decode):
";
print_r($userArrayB);
?>
How it works: This snippet shows two common ways to convert between arrays and objects in PHP. To convert an array to an object, you can simply type-cast it using `(object)`. Each key-value pair in the array becomes a public property of the new `stdClass` object. To convert an object back to an array, you can also use type-casting `(array)`, but this only converts public properties and prefixes private/protected properties. A more robust method, especially for objects that might contain nested data or need full property serialization, is to use `json_encode` to convert the object to a JSON string, and then `json_decode` with `true` to convert it back into an associative array.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs