PHP
Web Development
Coding
Array Conversion
Object-Oriented Programming

Convert a PHP object to an associative array

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In PHP, objects can be converted to associative arrays using the get_object_vars() function or by casting the object with (array). This is particularly useful when you need to extract data from an object to use in functions that require arrays or for debugging purposes. Below, we explore each method, their differences, and implications, with practical examples providing a deeper understanding of the subject.

Using get_object_vars()

The get_object_vars() function returns an associative array of defined properties of an object that are visible to the current scope. It's important to note that if a property is private or protected, it won't be returned unless the function is called in the scope where the property is defined.

Example

Consider the following class:

php
1class Person {
2    public $name = "John Doe";
3    protected $age = 30;
4    private $phone = '1234567890';
5}
6
7$person = new Person();
8$result = get_object_vars($person);
9print_r($result);

Output:

 
1Array
2(
3    [name] => John Doe
4)

In this example, only the public property $name is returned. The protected property $age and private property $phone are not included in the output.

Using (array) Casting

Casting an object to an array converts all visibility levels of an object’s properties into an associative array. The array keys preserve the visibility by prefixing properties' names with * for protected properties and the class name for private properties.

Example

Using the same Person class:

php
1class Person {
2    public $name = "John Doe";
3    protected $age = 30;
4    private $phone = '1234567890';
5}
6
7$person = new Person();
8$result = (array) $person;
9
10print_r($result);

Output:

 
1Array
2(
3    [name] => John Doe
4    [*age] => 30
5    [Personphone] => 1234567890
6)

Here, all properties are converted, including protected and private ones, with keys indicating their visibility.

Differences and When to Use

Featureget_object_vars()(array) Casting
VisibilityOnly accessible propertiesAll properties, with prefixes
Output StructureSimple associative arrayAssociative array with prefixes
Preferred UsePublic data extractionDebugging or specific needs where visibility must be retained

Considerations

  • Type Compatibility: When converting objects to arrays, ensure your properties are compatible with array values, as objects in properties will remain as objects.
  • Performance: The choice between get_object_vars() and (array) casting may depend on specific performance considerations in the context of your app.
  • Visibility Handling: Choose the method based on whether property visibility needs to be preserved in the output.

Deep Conversion of Nested Objects

To convert an object along with its nested objects to an associative array, you will need to recursively apply the conversion. Here’s a function that handles this:

php
1function objectToArray($obj) {
2    if (is_object($obj)) {
3        $obj = get_object_vars($obj);
4    }
5
6    if (is_array($obj)) {
7        return array_map(__FUNCTION__, $obj);
8    } else {
9        return $obj;
10    }
11}
12
13$complexObj = new stdClass();
14$complexObj->person = new Person(); // Using the earlier Person class
15$array = objectToArray($complexObj);
16
17print_r($array);

This will convert not only the top-level object but also any nested objects into associative arrays. This function uses recursion to delve deep into the object structure and convert it entirely.

Conclusion

Converting PHP objects to associative arrays can be implemented through either the get_object_vars() function or (array) casting, depending on the requirement of retaining property visibility and the scope of the properties you need to access. Each method is suitable for different scenarios in PHP programming, whether it's for data extraction for functional usage or debugging purposes.


Course illustration
Course illustration

All Rights Reserved.