In PHP, convert a PHP object to an associative array. A simple PHP array is a data structure that keeps one or more comparable sorts of information in a single name, while an associative array is not.
What’s PHP Array
Array is the data structure that stores one or more similar type of values in a single name but associative array is different from a simple PHP array.
What’s Associative Array
An associative array is an array that contains the string index. Rather than saving element values in linear index order, this saves element values associated with key values.
Also Checkout other dynamic MySQL query tutorials,
- Merge Two Array or Multiple Array in PHP
- How To Convert XML To Associative Array in PHP
- Remove Duplicates From Multidimensional Array
- How To Convert XSD into Array Using PHP
- Merge Two Array or Multiple Array in PHP
How to Convert a Object to an Associative Array
We can convert object to associative array using json_encode() and json_decode() method. We can also convert using PHP Type Casting object to an array.
Option 1 : Using json_encode() and json_decode() method
We can convert the PHP Object to an associative array using json_encode
and json_decode
methods.
The sample code:
class Employee { function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Creating the object $emp = new Employee('Parvez', 35); var_dump($emp); // Converting object to associative array $arr = json_decode(json_encode($emp), true); var_dump($arr);
Output:
object(Employee)#1 (2) { ["name"]=> string(6) "Parvez" ["age"]=> int(35) } array(2) { ["name"]=> string(6) "Parvez" ["age"]=> int(35) }
Option 2: Type Casting object to an array
Typecasting is the process of converting one data type variable to another. It can, for example, use PHP’s typecasting rules to transform a PHP object into an array.
Syntax:
$arr = (array) $obj;
The sample code:
class Employee { function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Creating the object $emp = new Employee('Parvez', 35); var_dump($emp); // Converting object to associative array $arr = (array)$emp; var_dump($arr);
Output:
object(Employee)#1 (2) { ["name"]=> string(6) "Parvez" ["age"]=> int(35) } array(2) { ["name"]=> string(6) "Parvez" ["age"]=> int(35) }
Option 3: Object to Array Conversion using get_object_vars
The get_object_vars() is also used to convert object to array in PHP. The get object var() function retrieves the specified object’s properties and returns an associative array of those declared object properties.
Syntax
get_object_vars(object)
The Example:
class Employee { function __construct($name, $age) { $this->name = $name; $this->age = $age; } } // Creating the object $emp = new Employee('Parvez', 35); var_dump(get_object_vars($emp));
Output:
array(2) { ["name"]=> string(6) "Parvez" ["age"]=> int(35) }