Computer >> Computer tutorials >  >> Programming >> PHP

Convert an object to associative array in PHP


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

Example

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

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