How to recursively convert object to array in PHP

Summary:

If you want to convert a deep php object to array, then you will need to take a recursive approach. Create a PHP function that will traverse an object and when you find another object, call the same function within itself. This way you will convert all of the objects into arrays.

Conversion of Object to Array in PHP

Introduction – Object to Array in PHP

Classes and Objects are fundamentals of object-oriented programming. A class is a blueprint or a master plan similar to a building’s map, while objects are instances based on a class blueprint, just as buildings are instances of a master plan. Once you have a class, you can define as many objects. These objects have the same set of attributes, but these attributes’ values can be different.

object to array in php

Besides attributes, a class can include some methods too. Here’s a detailed PHP guide about classes and objects. If you feel you’re lacking context here, make sure to read it; otherwise, basic knowledge about classes and objects in PHP would suffice for this article, where we’ll see how to convert an object to array in PHP.

Getting started

Before we start, let’s see a Customer class in PHP.  We’ll be converting its object to array PHP.

<?php
class Customer {
    public $name;
    protected $wallet_id;
    private $balance;
 
    function __construct($name, $wallet_id, $balance) {
        $this->name = $name;
        $this->wallet_id = $wallet_id;
        $this->balance = $balance;
    }
 
    function set_balance($balance) {
        $this->balance = $balance;
    }
 
    function set_walletId($wallet_id) {
        $this->wallet_id = $wallet_id;
    }
 
    function get_balance() {
        return $this->balance;
    }
 
    function get_walletId() {
        return $this->wallet_id;
    }
}
 
?>

So, here’s an elementary class. The class has three attributes: name, wallet_id, and balance. These attributes are preceded by keywords: public, protected, and private. These keywords signify the access modifier. As the name hints, public attributes can be accessed directly with an object, while the rest are more strict and cannot be accessed directly. 

There are a bunch of getters and setters for modifying and accessing the protected and private attributes because they are not directly accessible. These functions are public by default. Besides, there can be other class functions but let’s keep the class leans at the moment.


The construct function helps in creating objects. Let’s create a Customer object now.

$customer = new Customer("Wallace", "10346", 100000);

Let’s try out accessing these attributes and see what we get.

echo $customer->name.PHP_EOL;
echo $customer->wallet_id;

Here’s the output.

Wallace
PHP Fatal error:  Uncaught Error: Cannot access protected property Customer::$wallet_id

So, we see the customer name and a PHP fatal error. PHP throws an error because we’re trying to access a protected attribute. The same happens when you try to access public property.

Now, as we have a clear picture, it’s the right moment to see how to convert object to array in PHP.

Convert Object to Array in PHP – Basic

PHP supports type casting objects to arrays. Typecasting is converting a data type explicitly and here’s how to do it.

$customer_arr = (array) $customer;
var_dump($customer_arr);
/*
OUTPUT
array(3) {
  ["name"]=>
  string(7) "Wallace"
  ["*wallet_id"]=>  
  string(5) "10346"
  ["Customerbalance"]=>
  int(100000)
}
*/

The output reveals the protected attribute walet_id with a *, *wallet_id, and private attribute balance with the class name Customer, Customerbalance. That’s rather strange, but to your surprise, internally, the array looks like.

array (
  'name' => 'Wallace',
  '' . "\0" . '*' . "\0" . 'wallet_id' => '10346',
  '' . "\0" . 'Customer' . "\0" . 'balance' => 100000,
)

The wallet_id and balance have peculiar representations. Either way, you cannot access them because that compromises the access modifiers, remember protected and private. The rule of thumb is that they won’t be accessed and modified directly by PHP even if the object converts to an array.

These are essential caveats related to converting object to array in PHP. Next, we’ll see a recursive approach for this conversion.

Recursively convert object to array in PHP

Just as a multidimensional array can hold a nested array, a class can also have another class. Let’s refactor the Customer class to see how.

class BankAccount {
    public $branch_name;
    protected $wallet_id;
    private $balance;
 
    function set_balance($balance) {
        $this->balance = $balance;
    }
 
    function set_walletId($wallet_id) {
        $this->wallet_id = $wallet_id;
    }
 
    function get_balance() {
        return $this->balance;
    }
 
    function get_walletId() {
        return $this->wallet_id;
    }
}
class Customer {
    public $name;
    private $bank_account;
 
    function __construct($name, $bank_account) {
        $this->name = $name;
        $this->bank_account = $bank_account;
    }
 
    function get_bankAccount() {
        return $this->bank_account;
    }
 
    function set_bankAccount($bank_account) {
        $this->bank_account = $bank_account;
    }
 
}

So, we have added a BankAccount class, and the attributes wallet_id and balance now move to the Bank. The Customer gets the Bank class. If we try the same typecasting, we get this strange-looking output.

array (
  'name' => 'Wallace',
  '' . "\0" . 'Customer' . "\0" . 'bank_account' => 
  BankAccount::__set_state(array(
     'branch_name' => 'New Town',
     'wallet_id' => '10346',
     'balance' => 100000,
  )),
)

We have to deploy a recursive approach to convert the BankAccount object too. A great thing about a recursive approach is that it is general and can be used with any object regardless of its complexity. The code is as follows.

function object_to_array($obj) {
    //Find if an array is object
    if(is_object($obj)) {
        $obj = (array) $obj;
    }
    //If an array, recursively calls this function on every element.
    if(is_array($obj)) {
        $newArray = array();
        foreach($obj as $key => $val) {
            $newArray[$key] = object_to_array($val);
        }
    }
    else $newArray = $obj;
    return $newArray;
}

Now, let’s pass the customer object to this function and see the output.

Array
(
    [name] => Wallace
    [Customerbank_account] => Array       
        (
            [branch_name] => New Town     
            [*wallet_id] => 10346
            [BankAccountbalance] => 100000
        )

)

Voila! We have a proper multidimensional array that reflects the object structure and attributes. 

Conclusion

This article starts with a refresher on classes and objects and runs through a basic typecasting example, converting an object to array in PHP. The typecasting alone doesn’t work well if there are objects with references for other objects, so the article explains a recursive approach. The recursive approach is generalized, and it can deal with objects of any type and make-up. That’s a summary of the article, and if you have enjoyed it, feel free to pay a visit to FuelingPHP for excellent PHP articles and tutorials.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.


Article Categories

Article Tags

© 2022 Confident.Systems