Tuesday, February 16, 2016

[PHP] Convert Array & Object

1
2
3
4
5
// 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.
1
2
3
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.
1
2
3
function object_to_array($object) {
    return (array) $object;
}