Convert Object To Array in PHP

Last updated 1 year, 9 months ago | 723 views 75     5

Tags:- PHP

PHP | Convert Object To  Array

Converting an object to an array is a small thing that can be achieved by a single line of code. For this purpose, we need to use typecasting. Typecasting is a way to use/convert one data type variable into the other data type.

So, let's see an example

<?php

$obj = new stdClass;    // create an object
$obj->id = 1;
$obj->name = "Ram";
$obj->roll = 5;
$obj->subject = subject;

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

print_r( $array );    

?>


// output the result


Array
(
[id] => 1
[name] => Ram
[roll] => 5
[subject] => subject
)

Let's see a complex object so that the object-subject is itself an object.

<?php

$obj = new stdClass; // create object
$obj->id = 1;
$obj->name = "Ram";
$obj->roll = 5;
$obj->subject = new stdClass;     //complex object
$obj->subject->hindi = 'Hindi';
$obj->subject->eng = 'English';
$obj->subject->math = 'Math';


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


print_r( $array );


?>

// output the result
Array
(
[id] => 1
[name] => Ram
[roll] => 5
[subject] => stdClass Object         // This is still in object
	(
		[hindi] => Hindi
		[eng] => English
		[math] => Math
	)

)

To deal with this situation, some recursion is required to perform the conversion. For this, we need to check for an object, and if an object is found, it gives an array representation.

<?php

$obj = new stdClass; // create object
    $obj->id = 1;
    $obj->name = "Ram";
    $obj->roll = 5;
    $obj->subject = new stdClass;     //complex object
    $obj->subject->hindi = 'Hindi';
    $obj->subject->eng = 'English';
    $obj->subject->math = 'Math';


function objectToArray( $object )   // recursive function
    {
        if( is_object( $object ) )
        {
            $object = get_object_vars( $object );
        }else{
			return $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
(
    [id] => 1
    [name] => Ram
    [roll] => 5
    [subject] => Array
        (
            [hindi] => Hindi
            [eng] => English
            [math] => Math
        )

)

get_object_vars() : 
This function gets the properties of the given object. It returns an associative array of defined object properties for the specified object.


array_map():
The array_map() function sends each value of an array to a user-made function and returns an array with new values, given by the user-made function.