How to Convert an Object to Associative Array in PHP

Here are the two ways to convert an object to an associative array in PHP.

  1. Using json_encode() and json_decode() method.
  2. Type Casting object to an array.

Method 1: Using the json_encode() and json_decode() method

Syntax

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

Example

<?php 

class ST { 
 
  function __construct($mike, $eleven) 
  { 
    $this->var1 = $mike; 
    $this->var2 = $eleven; 
  } 
} 
 
// Create the object 
$st3 = new ST('Finn', 'Millie'); 
echo "Before conversion: \n"; 
var_dump($st3); 
 
// Convert object to associative array 
$arr = json_decode(json_encode($st3), true); 
echo "After conversion: \n"; 
var_dump($arr);

Output

Before conversion:
object(ST)#1 (2) {
 ["var1"]=>
 string(4) "Finn"
 ["var2"]=>
 string(6) "Millie"
}
After conversion:
array(2) {
 ["var1"]=>
 string(4) "Finn"
 ["var2"]=>
 string(6) "Millie"
}

You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions.

Method 2: Type Casting object to an array

Syntax

$arr = (array) $obj;

Example

<?php 

class ST { 
 
  function __construct($mike, $eleven) 
  { 
    $this->var1 = $mike; 
    $this->var2 = $eleven; 
  } 
} 
 
// Create the object 
$st3 = new ST('Finn', 'Millie'); 
echo "Before conversion: \n"; 
var_dump($st3); 
 
// Convert object to associative array 
$arr = (array) $st3; 
echo "After conversion: \n"; 
var_dump($arr);

We have to change one line from the Method 1 code.

$arr = (array) $st3;

Output

Before conversion:
object(ST)#1 (2) {
 ["var1"]=>
 string(4) "Finn"
 ["var2"]=>
 string(6) "Millie"
}
After conversion:
array(2) {
 ["var1"]=>
 string(4) "Finn"
 ["var2"]=>
 string(6) "Millie"
}

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.