Converting a PHP stdClass object into an array
Published on 2024-07-27 • Modified on 2024-07-27
This snippet shows how to convert a PHP stdClass object into an array. We can use this famous trick utilising the json_encode()
function and its reverse fonction json_decode()
. There also an example showing that using a cast does not work as it is not recursive. The StackOverflow link provides more explanation.
<?php
declare(strict_types=1);
namespace App\Controller\Snippet;
/**
* I am using a PHP trait to isolate each snippet in a file.
* This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
* or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
* Services are injected in the main controller constructor.
*/
trait Snippet311Trait
{
public function snippet311(): void
{
$stdClass = new \stdClass();
$stdClass->foo = 'bar';
$stdClass->object_property = new \stdClass();
$stdClass->object_property->foo2 = 'bar2';
echo '----- Nominal case OK ✅'.PHP_EOL;
echo '> original object:'.PHP_EOL;
$array = json_decode((string) json_encode($stdClass), true);
var_dump($stdClass);
echo '> as array:'.PHP_EOL;
var_dump($array);
echo PHP_EOL;
// With a cast, it doesn't work as the object_property is not converted into an array
echo '----- cast case, does not work ❌'.PHP_EOL;
var_dump((array) $stdClass);
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc Random snippet