php

How to convert an object to associative array in PHP

In this tutorial, we are going to see how to convert an object to associative array in PHP. An object is an instance of a class, while an array is a data structure that stores one or more similar types, an associative array is an array that stores values in association with keys.

We can convert an object into an array using two methods:

  • Using the json_encode() and json_decode() method.
  • Forced type conversions (type casting).

 

Convert an object to associative array using the json_encode() and json_decode() methods

Initially, the json_encode() function returns a JSON string for a given value. The json_decode() function transforms it into a PHP array.

Example:
 

 

<?php
   class Person {
      public function __construct($name, $age) {
         $this->name = $name;
         $this->age = $age;
      }
   }
   $obj = new Person("Emily", 20);
   echo "Before the conversion:".'</br>';
   var_dump($obj);
   $tab = json_decode(json_encode($obj), true);
   echo "After the conversion:".'</br>';
   var_dump($tab);
?>

Output:

Before the conversion: 
object(person)#1 (2) { 
   ["name"]=> string(5) "Emily" 
   ["age"]=> int(20) 
}

After the conversion: 
array(2) { 
   ["name"]=> string(5) "Emily" 
   ["age"]=> int(20) 
}
 

Convert an object to associative array using type casting

Typecasting is the approach of using a variable of one data type in different types. It is simply a type transformation.

<?php
   class Person {
      public function __construct($name, $age) {
         $this->name = $name;
         $this->age = $age;
      }
   }
   $obj = new Person("Emily", 20);
   echo "Before the conversion:".'</br>';
   var_dump($obj);
   $tab =(array)$obj;
   echo "After the conversion:".'</br>';
   var_dump($tab);
?>

Output:

Before the conversion: 
object(person)#1 (2) { 
   ["name"]=> string(5) "Emily" 
   ["age"]=> int(20) 
}

After the conversion: 
array(2) { 
   ["name"]=> string(5) "Emily" 
   ["age"]=> int(20) 
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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