Convert an object to associative array in PHP


To convert an object to associative array in PHP, the code is as follows−

Example

 Live Demo

<?php
   class department {
      public function __construct($deptname, $deptzone) {
         $this->deptname = $deptname;
         $this->deptzone = $deptzone;
      }
   }
   $myObj = new department("Marketing", "South");
   echo "Before conversion:"."
";    var_dump($myObj);    $myArray = json_decode(json_encode($myObj), true);    echo "After conversion:"."
";    var_dump($myArray); ?>

Output

This will produce the following output−

Before conversion:
object(department)#1 (2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
After conversion:
array(2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}

Example

Let us now see another example −

 Live Demo

<?php
   class department {
      public function __construct($deptname, $deptzone) {
         $this->deptname = $deptname;
         $this->deptzone = $deptzone;
      }
   }
   $myObj = new department("Marketing", "South");
   echo "Before conversion:"."
";    var_dump($myObj);    $arr = (array)$myObj;    echo "After conversion:"."
";    var_dump($arr); ?>

Output

This will produce the following output−

Before conversion:
object(department)#1 (2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}
After conversion:
array(2) {
   ["deptname"]=>
   string(9) "Marketing"
   ["deptzone"]=>
   string(5) "South"
}

Updated on: 26-Dec-2019

293 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements