Convert Object To Array With PHP

By Kevin Waterson

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.

/*** 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 );

Gracias a PHPro