PHP : Convert or Cast Array to Object & Object to Array

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.

[php]
// Echoing a PHP Array value
echo $array[‘value’];

// Echoing a PHP Object value
echo $object->value;
[/php]

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.

[php]
function array_to_object($array) {
return (object) $array;
}
[/php]

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.

[php]
function object_to_array($object) {
return (array) $object;
}
[/php]

Now, back to some Codeigniter coding :)


Comments

15 responses to “PHP : Convert or Cast Array to Object & Object to Array”

  1. Mihai Iorga

    “$return” ?

    1. Well spotted! Updated the post now :)

  2. Ernesto Vargas-Azofeifa

    Or you can do:
    $object = json_decode(json_encode($array), FALSE);

    1. I suspect this is a much more memory intensive way to do it and is not supported by versions of PHP <= 5.1 :/

      1. Good thing

      2. I know this is old post but (object) just converts first “dimension”. Multidimensional arrays will stay array except for the first dimension. So after using (object) on multidimensional array you still wont be able to use $object->value->subvalue; With json method the entire multidimensional array is converted to object.

  3. typo in function keyword (missed the c)

  4. There is a typo. Is not funtion is function.

  5. easy and helpful. thanks

  6. Bruno Veiga

    Thanks!

  7. Geek Support

    It’s worth bearing in mind that if you have something like $array[‘my-value’]; Converting that you won’t be able to use $object->my-value and will have to use something like $object->{‘my-value’} which isn’t quite so clean looking ;-)

  8. Mohammad Rahat Hossain

    Thanks buddy

  9. wow, so easy I couldnt imagine that it will be this precise .