How to convert an array to object in php?

by cali_green , in category: PHP General , a year ago

How to convert an array to object in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by darion , a year 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 , a year 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.