How to convert an Object to an Array in PHP

To convert a PHP object to an Array we simply typecast it as the below code:

example.php
<?php

class Student 
{
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$studentObject = new Student('Peter James', 20);
$studentArray = (array) $studentObject;

var_dump($studentArray);

Output:

array (size=2)
  'name' => string 'Peter James' (length=11)
  'age' => int 20

0 0 vote
Article Rating
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x