Convert an array to object in PHP

Convert an array to object in PHP

A class is an Object. We also name objects as instances.  once we define a class and then make many objects that belong to it.

Following way to convert an array to object in PHP

1 . Type Casting Array to object

we can use typecasting which is simply the explicit conversion of a data type. By using typecasting rules supported in PHP

Syntax for convert a PHP object to an array

 $object = (object) $array;

OR

2. Using Json Decode & Json Encode

JSON encoded string is accepted by json_decode function and converts it into a PHP variable and on the other hand, JSON encoded string for a given value is returned by json_encode

Syntax for convert a PHP array to object

 $object = json_decode(json_encode($array), FALSE);

OR

3. Using a loop

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

Tags

We are Recommending you:

Leave a comment

Comments