How to Convert a PHP Object to an Associative Array

  1. Using json_decode and json_encode
  2. Casting Object to an Array

This snippet will explain the ways of converting a PHP object to an associative array.

Below, you can find efficient ways to meet that goal.

A. Using json_decode and json_encode

The first method is applying json_decode and json_encode functions. The first function is capable of accepting JSON-encoded string and converting it into a PHP variable. The second one returns a JSON-encoded string for a particular value.

The syntax will look as follows:

$myArray = json_decode(json_encode($object), true);

For a better perception, check out the following example:

<?php
class sample {
      
    /* Member variables */
    var $var1;
    var $var2;
      
    function __construct( $par1, $par2 ) 
    {
        $this->var1 = $par1;
        $this->var2 = $par2;
    }
}
  
// Creating the object
$myObj = new sample(1000, "second");
echo "Before conversion: \n";
var_dump($myObj);
  
// Converting object to associative array
$myArray = json_decode(json_encode($myObj), true);
echo "After conversion: \n";
var_dump($myArray);
?>

Its outcome looks like this:

Before conversion: 
object(sample)#1 (2) {
  ["var1"]=>
  int(1000)
  ["var2"]=>
  string(6) "second"
}
After conversion: 
array(2) {
  ["var1"]=>
  int(1000)
  ["var2"]=>
  string(6) "second"
}

B. Casting Object to an Array

The second method we recommend is casting the object to an array. Normally, typecasting considers the utilization of one data type variable to the other data type. Simply, it is the explicit conversion of a data type. With it, one can convert a PHP object into an array with the help of type casting rules.

The syntax is as follows:

$myArray = (array) $myObj;

The example will look like this:

<?php 
class bag { 
	
	/* Member variables */
	var $item1; 
	var $item2; 
	var $item3; 
	
	function __construct( $par1, $par2, $par3) 
	{ 
		$this->item1 = $par1; 
		$this->item2 = $par2; 
		$this->item3 = $par3; 
	} 
} 

// Create myBag object 
$myBag = new bag("Mobile", "Charger", "Cable"); 
echo "Before conversion : \n"; 
var_dump($myBag); 

// Coverting object to an array 
$myBagArray = (array)$myBag; 
echo "After conversion : \n"; 
var_dump($myBagArray); 
?>

The output will look as follows:

Before conversion : 
object(bag)#1 (3) {
  ["item1"]=>
  string(6) "Mobile"
  ["item2"]=>
  string(7) "Charger"
  ["item3"]=>
  string(5) "Cable"
}
After conversion : 
array(3) {
  ["item1"]=>
  string(6) "Mobile"
  ["item2"]=>
  string(7) "Charger"
  ["item3"]=>
  string(5) "Cable"
}

What is an Associative Array

An object is considered an instance of a class. It is the base for a class and has allocated memory.

The data structure is capable of storing one or more similar type of values in a single name. The associative array is something different. An associative array is considered an array, containing string index.


Do you find this helpful?

Related articles