Porto

Convert Object To Array With PHP

Convert Object To Array With PHP

Converting an object to an array using PHP comes with a small gotcha. One would be forgiven for thinking it is merely a task of casting the object and the job can be completed with a single line of code. This works well for simple objects, however, the task increases in complexity in line with the objects complexity.

Consider the following object that is cast to an array.


<?php
    
/*** create an object ***/
    
$obj = new stdClass;
    
$obj->foo 'foo';
    
$obj->bar 'bar';
    
$obj->baz 'baz';

    
/*** cast the object ***/
    
$array = (array) $obj;

    
/*** show the results ***/
    
print_r$array );
?>

The result from the code above produces an array representation of the object. This is the desired result as shown here

Array
(
    [foo] => foo
    [bar] => bar
    [baz] => baz
)

Lets now increase the complexity of the object, so that the object bar is itself an object.


<?php
    
/*** a slightly more complex array ***/
    
$obj = new stdClass;
    
$obj->foo 'foo';
    
$obj->bar = new stdClass;
    
$obj->bar->baz 'baz';

    
/*** cast the object to array ***/
    
$array = (array) $obj;

    
/*** show the results ***/
    
print_r$array );
?>

From the code above, the issue becomes a little clearer, as the resulting array contains an instance of stdClass, and not an array.

Array
(
    [foo] => foo
    [bar] => stdClass Object
	(
	    [baz] => baz
	)
)

To remedy this situation, some recursion is required to check for an object, and if an object is found, it is give an array representation.


<?php
    
/*** a complex object ***/
    
$obj = new stdClass;
    
$obj->foo = new stdClass;
    
$obj->foo->baz 'baz';
    
$obj->bar 'bar';

    
/**
    *
    * Convert an object to an array
    *
    * @param    object  $object The object to convert
    * @reeturn      array
    *
    */
    
function objectToArray$object )
    {
        if( !
is_object$object ) && !is_array$object ) )
        {
            return 
$object;
        }
        if( 
is_object$object ) )
        {
            
$object get_object_vars$object );
        }
        return 
array_map'objectToArray'$object );
    }

    
/*** convert the array to object ***/
    
$array objectToArray$obj );

    
/*** show the array ***/
    
print_r$array );
?>

Now the results show a multi-dimensional array which is a true array representation of the object.

Array
(
    [foo] => Array
        (
            [baz] => baz
        )

    [bar] => bar
)