To convert a PHP object to an associative array, you can use built-in functions or manual techniques. Below are the most common methods, explained in detail with examples.
1. Using get_object_vars()
The get_object_vars()
function returns the public properties of an object as an associative array. This is the simplest method if the object’s properties are public.
Example:
class User {
public $name = "John";
public $age = 30;
private $password = "secret"; // Private properties are ignored
}
$user = new User();
$array = get_object_vars($user);
print_r($array);
Output:
Array (
[name] => John
[age] => 30
)
Limitations:
- Only returns public properties (private/protected properties are excluded).
- Works only in the object’s scope (e.g., if called outside the class, private properties won’t appear).
2. Typecasting to an Array
You can cast the object to an array using (array)
. This converts all properties (including private/protected) into array keys, but with visibility prefixes (e.g., *
for protected, class name for private).
Example:
class User {
public $name = "John";
protected $email = "john@example.com";
private $password = "secret";
}
$user = new User();
$array = (array)$user;
print_r($array);
Output:
Array (
[name] => John
[*email] => john@example.com // Protected property
[Userpassword] => secret // Private property (class name prefixed)
)
Note:
The visibility prefixes (e.g., *
or Userpassword
) are part of PHP’s internal representation. You can sanitize the keys using string manipulation if needed.
3. JSON Encoding/Decoding
Convert the object to a JSON string and then decode it into an associative array. This works well for nested objects and public properties.
Example:
class User {
public $name = "John";
public $age = 30;
}
$user = new User();
$json = json_encode($user);
$array = json_decode($json, true); // `true` returns an associative array
print_r($array);
Output:
Array (
[name] => John
[age] => 30
)
Limitations:
- Only serializes public properties.
- Objects with non-serializable data (e.g., closures) will fail.
4. Recursive Conversion for Nested Objects
If your object contains nested objects (e.g., properties that are themselves objects), use a recursive function to convert everything to arrays.
Example:
function objectToArray($obj) {
if (is_object($obj)) {
$obj = (array)$obj;
}
if (is_array($obj)) {
return array_map(__FUNCTION__, $obj);
}
return $obj;
}
class Profile {
public $hobby = "Reading";
}
class User {
public $name = "John";
public $profile; // Nested object
public function __construct() {
$this->profile = new Profile();
}
}
$user = new User();
$array = objectToArray($user);
print_r($array);
Output:
Array (
[name] => John
[profile] => Array (
[hobby] => Reading
)
)
5. Using Reflection (Advanced)
The ReflectionClass
can access all properties (including private/protected) of an object. This is useful for debugging or complex conversions.
Example:
class User {
private $id = 101;
protected $email = "john@example.com";
public $name = "John";
}
$user = new User();
$reflection = new ReflectionClass($user);
$properties = $reflection->getProperties();
$array = [];
foreach ($properties as $property) {
$property->setAccessible(true); // Bypass visibility
$array[$property->getName()] = $property->getValue($user);
}
print_r($array);
Output:
Array (
[id] => 101
[email] => john@example.com
[name] => John
)
Note:
This method requires PHP’s Reflection API and bypasses property visibility rules.
Summary of Methods
Method | Use Case | Handles Private/Protected? | Nested Objects? |
---|---|---|---|
get_object_vars() | Simple conversion of public properties | ❌ | ❌ |
Typecasting (array) | Quick conversion with visibility prefixes | ✔️ (with prefixes) | ❌ |
JSON encode/decode | Public properties and nested objects | ❌ | ✔️ |
Recursive function | Complex objects with nested structures | ❌ | ✔️ |
Reflection API | Access all properties (including private) | ✔️ | ❌ |
When to Use Which Method?
- Public Properties Only: Use
get_object_vars()
or JSON encoding. - All Properties (Including Private): Use typecasting (with key sanitization) or Reflection.
- Nested Objects: Use JSON encoding or a recursive function.
By choosing the right method, you can efficiently convert PHP objects to associative arrays based on your needs.