Convert object to an array in PHP.

In PHP applications, we often work with data in various formats such as strings, arrays, and objects. Sometimes we need to convert a PHP object to an associative array to process the data more efficiently or to make it compatible with certain functions.

An object is an instance of a class that has properties and methods, while an associative array uses string keys to store key−value pairs. Converting objects to arrays allows easier data manipulation and serialization.

Using json_encode() and json_decode()

The json_encode() function converts a PHP value to JSON string, and json_decode() converts it back to a PHP array when used with the second parameter set to true

<?php
    class Student {
        public function __construct($firstname, $lastname) {
            $this->firstname = $firstname;
            $this->lastname = $lastname;
        }
    }
    
    $myObj = new Student("Alex", "Stokes");
    echo "Before conversion:
"; var_dump($myObj); $myArray = json_decode(json_encode($myObj), true); echo "\nAfter conversion:
"; var_dump($myArray); ?>
Before conversion:
object(Student)#1 (2) {
  ["firstname"]=>
  string(4) "Alex"
  ["lastname"]=>
  string(6) "Stokes"
}

After conversion:
array(2) {
  ["firstname"]=>
  string(4) "Alex"
  ["lastname"]=>
  string(6) "Stokes"
}

Using Typecasting

Typecasting with (array) directly converts an object to an array. This method is faster and more straightforward −

<?php
    class Bag {
        public function __construct($item1, $item2, $item3) {
            $this->item1 = $item1;
            $this->item2 = $item2;
            $this->item3 = $item3;
        }
    }
    
    $myBag = new Bag("Books", "Ball", "Pens");
    echo "Before conversion:
"; var_dump($myBag); $myBagArray = (array)$myBag; echo "\nAfter conversion:
"; var_dump($myBagArray); ?>
Before conversion:
object(Bag)#1 (3) {
  ["item1"]=>
  string(5) "Books"
  ["item2"]=>
  string(4) "Ball"
  ["item3"]=>
  string(4) "Pens"
}

After conversion:
array(3) {
  ["item1"]=>
  string(5) "Books"
  ["item2"]=>
  string(4) "Ball"
  ["item3"]=>
  string(4) "Pens"
}

Comparison

Method Performance Private Properties Best For
JSON encode/decode Slower Includes only public Simple objects
Typecasting Faster Includes all properties Direct conversion

Conclusion

Both methods effectively convert objects to arrays. Use typecasting for better performance and when you need all properties, or JSON methods for simple public−only conversions.

Updated on: 2026-03-15T08:10:59+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements