Current Location: Home> Latest Articles> Common Ways to Convert Arrays to Objects in PHP: Examples and Applications

Common Ways to Convert Arrays to Objects in PHP: Examples and Applications

M66 2025-09-24

Common Ways to Convert Arrays to Objects in PHP

In PHP, converting arrays to objects is a common task, especially when dealing with data structures. Below are some of the most common methods for doing this:

Using the stdClass Class

stdClass is a standard class provided by PHP to create an empty object. You can store the key-value pairs of an array as properties of this object.

$array = [ 'name' => 'John Doe', 'age' => 30 ];
$object = new stdClass();
foreach ($array as $key => $value) {
    $object->$key = $value;
}

Using the json_decode() Function

The json_decode() function can decode a JSON string into a PHP object. You can convert an array into a JSON string and then use json_decode() to decode it back into an object.

$array = [ 'name' => 'John Doe', 'age' => 30 ];
$json = json_encode($array);
$object = json_decode($json);

Using Third-Party Libraries

In addition to the built-in functions and classes, PHP also supports third-party libraries for array-object conversion, such as:

  • ArrayObject class
  • Hydrator library

Practical Example

Let's assume we have an array of user data:

$users = [
    [ 'id' => 1, 'name' => 'John Doe', 'email' => 'john@example.com' ],
    [ 'id' => 2, 'name' => 'Jane Doe', 'email' => 'jane@example.com' ],
];

We can use any of the above methods to convert the array into objects. Below are the practical examples for each method:

Using the stdClass Class:

foreach ($users as $user) {
    $object = new stdClass();
    $object->id = $user['id'];
    $object->name = $user['name'];
    $object->email = $user['email'];
}

Using the json_decode() Function:

foreach ($users as $user) {
    $json = json_encode($user);
    $object = json_decode($json);
}

Using the ArrayObject Class:

foreach ($users as $user) {
    $object = new ArrayObject($user);
}

By using any of the above methods, we can convert an array of user data into an object, making it easier to work with the data in the program.

These are the common ways to convert arrays to objects in PHP, along with practical examples. You can choose the method that best fits your needs for handling data structures.