How To Convert Object To Array In Php

When working with PHP, you’ll often find yourself working with different data types such as objects and arrays. In some cases, you may need to convert an object to an array to more easily manipulate the data or to pass it to a specific function that expects an array as input. In this blog post, we’ll explore different ways to convert an object to an array in PHP.

Method 1: Using the get_object_vars() function

The get_object_vars() function is a built-in PHP function that returns an associative array containing all the public properties of an object. To use this function, simply pass the object as an argument:

$obj = new stdClass();
$obj->name = "John Doe";
$obj->age = 30;

$array = get_object_vars($obj);
print_r($array);
    

This will output:

Array
(
    [name] => John Doe
    [age] => 30
)
    

Method 2: Using type casting

Type casting is a way to explicitly inform PHP that you want to convert a variable from one data type to another. To convert an object to an array, simply cast the object to an array using the (array) syntax:

$obj = new stdClass();
$obj->name = "Jane Doe";
$obj->age = 28;

$array = (array) $obj;
print_r($array);
    

This will output:

Array
(
    [name] => Jane Doe
    [age] => 28
)
    

Method 3: Using the json_encode() and json_decode() functions

Another way to convert an object to an array in PHP is to use the json_encode() function to convert the object to a JSON string and then use the json_decode() function to convert the JSON string back to an array. To do this, simply pass the object as an argument to the json_encode() function and then pass the resulting JSON string to the json_decode() function with the second parameter set to true:

$obj = new stdClass();
$obj->name = "Alice";
$obj->age = 25;

$json = json_encode($obj);
$array = json_decode($json, true);
print_r($array);
    

This will output:

Array
(
    [name] => Alice
    [age] => 25
)
    

Conclusion

In this blog post, we’ve explored three different methods to convert an object to an array in PHP: using the get_object_vars() function, type casting, and using the json_encode() and json_decode() functions. Depending on your specific use case, you can choose the most suitable method for your needs.