How to convert an object properties into an array in php?

Member

by domenico , in category: PHP General , 4 months ago

How to convert an object properties into an array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 4 months ago

@domenico 

To convert an object's properties into an array in PHP, you can use the get_object_vars() function. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Person {
    public $name;
    public $age;
    public $city;
    
    public function __construct($name, $age, $city) {
        $this->name = $name;
        $this->age = $age;
        $this->city = $city;
    }
}

$person = new Person("John", 25, "New York");

$propertiesArray = get_object_vars($person);
print_r($propertiesArray);


Output:

1
2
3
4
5
6
Array
(
    [name] => John
    [age] => 25
    [city] => New York
)


In this example, the get_object_vars() function is used to convert the object's properties into an associative array. The resulting array will have property names as keys and their corresponding values.