PHP Object to Array Conversion
PHP Object to Array Conversion

PHP Object to Array Conversion – 2 Easy Methods

PHP Object to Array Conversion – 2 Easy Methods

In PHP, we can convert an object to an array using typecasting or by using built-in functions like get_object_vars() or json_decode(). Here’s how we can do it:

Method 1: Typecasting

// Define our object
$object = new stdClass();
$object->property1 = 'value1';
$object->property2 = 'value2';

// Convert object to array using typecasting
$array = (array) $object;

// Output the array
print_r($array);

 

Output will be an associative array:

Array
(
    [property1] => value1
    [property2] => value2
)

 

Method 2: Using built-in function get_object_vars():

// Define your object
$object = new stdClass();
$object->property1 = 'value1';
$object->property2 = 'value2';

// Convert object to array using get_object_vars()
$array = get_object_vars($object);

// Output the array
print_r($array);

Output will be an associative array just like the previous one:

Array
(
    [property1] => value1
    [property2] => value2
)

 

Method 3: Using built-in function json_decode() & json_encode()

// Define your object
$object = new stdClass();
$object->property1 = 'value1';
$object->property2 = 'value2';

// Convert object to array using JSON
$array = json_decode(json_encode($object), true);

// Output the array
print_r($array);

 

Output will be as like as the previous examples:

Array
(
    [property1] => value1
    [property2] => value2
)
 That's all for today! see you in another one! Till then, Bye!!

Editorial Staff

A Learner and trying to share what I learned!