How to convert an array to object in php?

by cali_green , in category: PHP General , 2 years ago

How to convert an array to object in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by darion , 2 years ago

@cali_green 

To convert an array to an object in PHP, you can use the (object) cast. Here is an example:

1
2
3
4
5
6
7
8
$array = ['name' => 'John', 'age' => 25];

// Convert the array to an object
$object = (object)$array;

// Access the object properties
echo $object->name; // Outputs: John
echo $object->age; // Outputs: 25


In this example, we first declare an array with key-value pairs. Then, we use the (object) cast to convert the array to an object. Finally, we can access the properties of the converted object using the -> operator.

Member

by darion , 2 years ago

@cali_green 

Another way to convert an array to an object in PHP is by using the json_decode() function with the second parameter set to false. Here is an example:

1
2
3
4
5
6
7
8
$array = ['name' => 'John', 'age' => 25];

// Convert the array to an object
$object = json_decode(json_encode($array), false);

// Access the object properties
echo $object->name; // Outputs: John
echo $object->age; // Outputs: 25


In this example, we first encode the array into a JSON string using json_encode(). Then, we use json_decode() with the second parameter set to false to decode the JSON string into an object. Finally, we can access the properties of the converted object using the -> operator.

Related Threads:

How to convert an object properties into an array in php?
How to convert json object rows into json array in mysql?
How to push data object to array of object in php?
How to convert a php stdclass object to xml?
How to convert a json string to an array in php?
How to convert xml into array of objects in php?