PASSWORD RESET

Your destination for complete Tech news

PHP

How to convert a PHP object to an associative array?

329 0
< 1 min read

To convert a PHP object to an associative array, you can use the get_object_vars function. This function returns an associative array of an object’s properties.

Here’s an example of how you can use it:

$object = new stdClass;
$object->foo = 'bar';
$object->baz = 'qux';

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

This will output the following array:

Array
(
    [foo] => bar
    [baz] => qux
)

Alternatively, you can also cast the object to an array using the (array) operator:

$array = (array) $object;
print_r($array);

This will also output the same associative array as the get_object_vars function.

Note that the get_object_vars function only works with object properties that are publicly accessible. If you have private or protected properties, they will not be included in the resulting array.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.