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)
phpAn 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 stdClassFunctions used in this recipe
- get_object_vars — Returns the accessible properties of an object as an array.
- json_encode — Converts a value to a JSON string.
- json_decode — Parses a JSON string.