Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Convert an object to associative array in PHP
To convert an object to associative array in PHP, you can use several methods. The most common approaches are type casting with (array) and using json_encode() with json_decode().
Method 1: Using JSON Encode/Decode
This method converts the object to JSON string first, then decodes it back as an associative array ?
<?php
class department {
public function __construct($deptname, $deptzone) {
$this->deptname = $deptname;
$this->deptzone = $deptzone;
}
}
$myObj = new department("Marketing", "South");
echo "Before conversion:<br>";
var_dump($myObj);
$myArray = json_decode(json_encode($myObj), true);
echo "After conversion:<br>";
var_dump($myArray);
?>
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"
}
Method 2: Using Type Casting
The simpler approach using direct type casting to convert object to array ?
<?php
class department {
public function __construct($deptname, $deptzone) {
$this->deptname = $deptname;
$this->deptzone = $deptzone;
}
}
$myObj = new department("Marketing", "South");
echo "Before conversion:<br>";
var_dump($myObj);
$arr = (array)$myObj;
echo "After conversion:<br>";
var_dump($arr);
?>
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"
}
Comparison
| Method | Handles Private Properties | Performance | Use Case |
|---|---|---|---|
| JSON Encode/Decode | Only public properties | Slower | Clean associative arrays |
| Type Casting | All properties (with special keys) | Faster | Quick conversion |
Conclusion
Use JSON encode/decode for clean associative arrays with only public properties. Use type casting (array) for faster conversion when you need all object properties including private ones.
Advertisements
