Codeigniter – Convert an array to object

Created at: May 15, 2014; Last update: May 15, 2014

I usually use the results that come from the models as objects (not as arrays). However, there are moments when I need to work with the results before sending them to the view. In this case, getting the results from the model as an array is preferable. But, when I send them to the view, I would like to work with objects. So now I need to convert the array into an object. I found the best answer to this problem on the famous stackoverflow (

There are two solutions:

1. First one would be to iterate the array and transform it to an object:

As you can see, we made an object with stdClass, which is an empty (generic) class. And then we used the keys of the array as methods for this class, methods that will have the values that the array had.

2. The second solution, especially if you want to convert the sub-arrays recursively (in case you have a multi-dimensional array). Take note that it has a 2-3x performance hit over the looping approach (because of the sub-arrays, of course).

Also, I found out that you can simply convert an object into an array by type-casting it.

Please, refrain from comments like: “Don’t you know you can also retrieve results as array from the model?”. Yes. I know I can.

One thought on “Codeigniter – Convert an array to object

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.