
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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:"."
"; 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 −
<?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" }
- Related Articles
- Convert object to an array in PHP.
- PHP array_push() to create an associative array?
- PHP Associative Array
- PHP Pushing values into an associative array?
- How to access an associative array by integer index in PHP?
- How to build dynamic associative array from simple array in php?
- Remove duplicated elements of associative array in PHP
- How to get numeric index of associative array in PHP?
- How to convert an array to SimpleXML in PHP?
- How to convert an object array to an integer array in Java?
- Creating an associative array in JavaScript?
- How to convert an object into an array in JavaScript?
- Associative Arrays in PHP
- How to convert an object to byte array in java?
- PHP program to add item at the beginning of associative array

Advertisements