PHP: Recursively convert an object to an array

June 16, 2010

When pulling in array from outside data sources you often receive an array back. The problem is that sometimes even though you know you should have an array your application does not and therefore assigns it to the stdObject object, which of course is nothing. To make it usable you must convert it back into an array. With a simple object that may be as simple as a cast, but when you are working with large complex datasets that may be several layers deep you need to make sure you get at all of them. Enter beautiful recursion. After playing with PHPs array_walk_recursive() for a bit I hit on a custom recursive function that does exactly the job. Simply pass it your object and it will munch away at it trying to convert it into a PHP array. Take a gander at the code for this below.

function object_to_array($obj) {
    if(is_object($obj)) $obj = (array) $obj;
    if(is_array($obj)) {
        $new = array();
        foreach($obj as $key => $val) {
            $new[$key] = object_to_array($val);
        }
    }
    else $new = $obj;
    return $new;       
}