Convert a PHP object into an array

Jacob Allred
#web-dev

SOAP loves to throw objects of objects of objects back at you when you make a call. There isn’t anything terribly wrong with that, but it makes it a bit hard to loop through the object’s properties using a foreach loop. get_object_vars can convert an object to an array, but leaves any objects contained within the object as objects, which makes it sort of pointless by itself. So here is a function that converts ALL of the objects in an object to arrays.

function conv_obj($Data){
    if(!is_object($Data) && !is_array($Data)) return $Data;
 
    if(is_object($Data)) $Data = get_object_vars($Data);
 
    return array_map('conv_obj', $Data);
}

First, we pass the object into the function. If the object isn’t actually an object or an array, then we return it as-is.

If it is an object, then we use get_object_vars to convert the object’s properties into an array.

Last, we use array_map to put all of the elements of $Data (the passed in object/array) through the same conv_obj function that we are already using so that all of the elements in the entire object/array are converted into arrays.

Nifty, eh?

PS- I didn’t write this code, which should be obvious by the lack of curly braces in the if statements.

For use in a class

function ConvertObjectToArray($Data){
    if(!is_object($Data) && !is_array($Data)){
        return $Data;
    }
 
    if(is_object($Data)){
        $Data = get_object_vars($Data);
    }
 
    return array_map(array($this,'ConvertObjectToArray'), $Data);
}