Convert object to array in PHP?

In this tutorial explained of convert object to array in php. This post will give you a easy example of convert stdclass object to array in php. I have explain php object to array convert and will give simple example with a solution. You will learn php convert object to array example.

Converting an object to an array in PHP is common task that can be accomplished in several manner. PHP provides multiple methods to archived this.

How to convert object to array in PHP?

The object can be converted to array in PHP by following method.

  • Type casting object to array: Type-casting means casting the data types from one to another. This is also one of the most used method to convert it.
  • Using get_object_vars(): function returns an associtive array to defined object properties for the specified object.
  • Using json decode and json encode: JSON encode function returns encoded string given a specific value which again needs to be decoded using JSON decode function. You can easily use in php.
1. Convert objects using Type Casting

You can directly cast the object to an array. This method used to simply convert object to array in PHP

Example 1:
<?php
    class MyNewClass {
        
    }
    
    $myNewObject = new MyNewClass;
    $myNewObject->id = 1;
    $myNewObject->title = "newposts";
    $myNewObject->description = "This is new posts";
    
    $nArray = (array) $myNewObject;
    print_r($nArray);
?>
Output:
Array
(
    [id] => 1
    [title] => newposts
    [description] => This is new posts
)
2. Convert object to array using get_object_vars()

This function returns an associative array containing all the properties of an object.

class MyNewClass {
    public $item1 = 'itemvalue1';
    public $item2 = 'itemvalue2';
}

$newobj = new MyNewClass();

$nArray = get_object_vars($newobj);

print_r($n_array);
Output:
Array 
(
    [item1] => itemvalue1
    [item2] => itemvalue2
)
3. php object to array using json_decode and json_encode

Initially json_encode() function return a JSON encoded string for a given specific value. The json_decode() function changes over it into a PHP array. You can consider following example.

<?php
    class user {
        public function __construct($grade, $position) 
        {
            $this->grade = $grade;
            $this->position = $position;
        }
    }
    $myNewObj = new user("A", "1");
    echo "Before used";
    var_dump($myNewObj);
    $myNewArray = json_decode(json_encode($myNewObj));
    echo "After used";
    var_dump($myNewArray);
?>
Output:
Before user:
Object(user)#1 (2) { ["grade"]=> string(4) "A" ["position"]=> string(6) "1"}
After user:
array(2) { ["grade"]=> string(4) "A" ["position"]=> string(6) "1"}

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *