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.

<?php
/*** create an object ***/
$obj = new stdClass;
$obj-&gt;foo = 'foo';
$obj-&gt;bar = 'bar';
$obj-&gt;baz = 'baz';</code></code>/*** cast the object ***/
$array = (array) $obj;

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

Gracias a PHPro

Leave a Reply