Recursively Convert PHP Object to Array: 5 Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Conversion of 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 lack context here, 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 an array in PHP.

PHP Class Code Example

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.

There can be other class functions, but let’s keep the class leans now.

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 the 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 objects to arrays in PHP.

Next, we’ll see a recursive approach for this conversion.

Recursively convert objects to arrays in PHP

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

Recursive PHP Objects to Arrays Code Example

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. 

How to Convert Objects to Arrays in PHP

This article starts with a refresher on classes and objects and runs through a basic typecasting example, converting an object to an array in PHP.

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 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.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.