Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to convert an object to an array

Short answer

get_object_vars() returns an object's public properties:

<?php
 
class Point
{
    public function __construct(public int $x, public int $y) {}
}
 
echo json_encode(get_object_vars(new Point(3, 4)));

Output:

{"x":3,"y":4}

Nested objects

get_object_vars() converts the top level only. A whole tree is turned into arrays through JSON:

<?php
 
$data = json_decode('{"user":{"name":"Anna","tags":["php"]}}');
 
$array = json_decode(json_encode($data), true);
 
var_dump(is_array($array['user']));
echo $array['user']['tags'][0];

Output:

bool(true)
php

An array to an object

The reverse conversion is a type cast:

<?php
 
$user = (object) ['name' => 'Anna', 'age' => 30];
 
echo $user->name, ' ', get_class($user);

Output:

Anna stdClass

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.