Convert Array to Object & Object to Array in PHP

Manuel Avelar
Aug 29, 2017 · 1 min read

I love PHP Objects. Given an option of returning any data as an Array or Object, I would go for Objects.

PHP Objects are clean and easy to write.

// Echoing a PHP Array value echo $array['value']; // Echoing a PHP Object value echo $object->value;

Now to the conversion (casting) of a PHP Array into a PHP Object. This is very simple. I just type cast the Array as an Object when returning it.

function array_to_object($array) { return (object) $array; }

The above is just an example. You do not need a PHP function to convert an Array into an Object. The (object) function will do that to any PHP Array. If you ever need to change an Object into an Array, then use the (array) type casting function.

function object_to_array($object) { return (array) $object; }

Happy coding!


Originally published at mavelar.com on August 29, 2017.

)

Manuel Avelar is a web developer from San Pedro Sula, Honduras. With more than +12 years of experience he’s worked for companies and freelance.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade