How to Convert an Array to Object in PHP

As a developer, you may have come across situations where you need to convert an array into an object.

This can be useful when you want to access the data in a more convenient and organized manner.

PHP provides a simple way to convert arrays into objects, and in this tutorial, we’ll go over the process step by step.


Understanding Arrays and Objects in PHP

Before diving into the conversion process, it’s important to understand the differences between arrays and objects in PHP.

An array is a collection of values that are stored under a single variable name and can be accessed by an index or key.

On the other hand, objects are instances of a class and consist of variables and functions that can be accessed using the “->” operator.

Converting an Array to an Object

The easiest way to convert an array to an object in PHP is by using the (object) casting operator.

This operator converts the array into an object, and the keys of the array become properties of the object.

Here’s an example:

$array = [
    "name" => "John",
    "age" => 30,
    "country" => "USA"
];

$object = (object)$array;

echo $object->name;
// Output: John

Another way to convert an array to an object is by using the stdClass class, which is a predefined class in PHP that allows you to create an object without any methods.

Here’s an example:

$array = [
    "name" => "John",
    "age" => 30,
    "country" => "USA"
];

$object = new stdClass();

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

echo $object->name;
// Output: John

In the example above, we used the foreach loop to iterate through the array and assign each key-value pair to the object as a property.


Conclusion

Converting an array to an object in PHP is a simple process that can be done in just a few lines of code.

Whether you choose to use the (object) casting operator or the stdClass class, the result will be the same – an object that allows you to access the data in a more organized and convenient manner.

With this knowledge, you’ll be able to easily convert arrays into objects in your PHP projects.