Skip to content

Instantly share code, notes, and snippets.

@victorbstan
Created December 17, 2010 04:18
Show Gist options
  • Save victorbstan/744478 to your computer and use it in GitHub Desktop.
Save victorbstan/744478 to your computer and use it in GitHub Desktop.
recursively cast a PHP object to array
<?php
/*
This function saved my life.
found on: http://www.sitepoint.com/forums//showthread.php?t=438748
by: crvandyke
It takes an object, and when all else if/else/recursive functions fail to convert the object into an associative array, this one goes for the kill. Who would'a thunk it?!
*/
$array = json_decode(json_encode($object), true);
@iam-raihan
Copy link

iam-raihan commented Aug 3, 2020

just in case performance matters

function objectToArray($object)
{
    if(!is_object($object) && !is_array($object)) {
        return $object;
    }

    return array_map('objectToArray', (array) $object);
}

from SO

@jonyen
Copy link

jonyen commented Dec 29, 2020

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

Absolutely brilliant. You, sir, are a genius.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment