Php Convert object to Associative Array


Php Convert object to Associative Array : We sometimes need to convert the php objects to associative array. An Object is converted to array which contains the keys that are member variables and values are object’s property. Here in this tutorial we are going to explain how you can convert php objects as associative array.


Php Convert object to Associative Array

Let us create a simple php object

Create Php Object : Example

<?php
$object = new StdClass;
$object->firstName = "John";
$object->lastName = "Dee";

?>

Php objects are accessed in php as below-

Create Php Object : Example

<?php
echo $object->firstName;
echo $object->lastName;

?>

The above example will give you the first name and last name.

Now let us convert the above php object in associative array –

Convert PHP object to Associative Array Example

Php Convert object to Associative Array : Example

<?php
$object = new StdClass;
$object->firstName = "John";
$object->lastName = "Dee";

$array = (array)$object;
echo $array['firstName']."<br>";
echo $array['lastName']."<br>";
?>

Try it »

$array[‘firstName’] give you the first name and $array[‘lastName’] will give you last name as associative key pair value. If you run the above example it will produce the following output –

Php Convert object to Associative Array

Exception : Some complex object such as private, protected variable are not converted to array properly using this method.

Advertisements

Add Comment

📖 Read More