PHP – Convert Array to Object & Object to Array

Hi guys in this tutorial we will learn how to type cast or convert an array into object and object into array. It is simple to type cast a value in php. You will see how it is easy to change type in php for variable value. Let us see example to get understand in better way.

 

How we print array value?

echo $array[‘value’];

 

How we print object value ?

echo $object->value;

Now we got how to print array and object value in PHP.

 

How to convert an array into an object in PHP ?

$object = (object) $array;

How to convert an object into an array in PHP ?

$array = (array) $object;

Now we can create a common function for both type casting instead of writing above scripts and can reuse it in PHP page in one project.

 

Function to convert an array into an object


function array_into_object()

{

$object = (object) $array;

return $object;

}

 

Function to convert an object into an array


function object_into_array()

{

$array = (array) $object;

return $array;

}

 

For type casting we can use above methods and put in common file to use any page in a single project. You do not need to use stdClass for type casting. If you have any query please feel free to write in below comment box.

 

Leave a Comment