Convert PHP object to associative array

During PHP development, you may never come across the need for this functionality, but its an extremely good piece of knowledge to have within your arsenal. If you’ve been using the Laravel PHP framework lately, this will be highly relevant to your development work.

Now, I don’t know about you, but within PHP, I detest reading objects, I’d much rather have them as associative array’s. I don’t know why exactly, but that’s just me.

2 PHP Object to Associative Array Solutions

Solution 1 – Using json_decode & json_encode

Here is the nice, quick, one line magical piece of code that converts your object to an associative array. With the following line of code, replace the $object variable with the name of your object variable you want to convert.

$myAssociativeArray = json_decode(json_encode($object), true);// Converts the object to an associative array

The $object variable above contained the following when using var_dump($object) –

public 'hexBlack' => string '#000000' (length=7)
public 'hexRed' => string '#FF0000' (length=7)
public 'hexMaroon' => string '#800000' (length=7)
public 'hexYellow' => string '#FFFF00' (length=7)

Meaning that you can access the values like this –

echo $object->hexBlack; // outputs #000000

And after the conversion took place, the $myAssociativeArray contained the following when using var_dump($myAssociativeArray)-

array (size=4)'hexBlack' => string 
'#000000' (length=7)'hexRed' => string 
'#FF0000' (length=7)'hexMaroon' => string '#800000' (length=7