Convert an object to associative array in PHP

PHPServer Side ProgrammingProgramming

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:"."\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 −

 Live Demo

<?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"
}
raja
Published on 26-Dec-2019 14:50:05
Advertisements