Sometimes working with PHP we need to convert objects into arrays for implement array functions or reduce looping from our code. Here, we will see two methods to convert objects into associative arrays.
Before starting let’s understand what is an object in PHP. An object is an instance of a class that has specific memory allocated. While associative arrays are generally used to store key-value pairs.
Here, we will see two methods to convert objects to arrays in PHP
- Using json_encode and json_decode
- Using type casting
Both methods work similarly. In type casting, we can convert a type of variable into another type. In the JSON method, first, we convert objects into JSON and then we convert JSON into an array.
Using json_encode and json_decode
Here, we will convert an object into a JSON string and then convert the JSON string into an associative array. We will use json_encode() and json_decode() functions. Below is a syntax for converting an object to an array using the JSON function:
$newArray = json_decode(json_encode($object), true);
Let’s take a practical example of it.
<?php
class test {
/* Member variables */
var $val1;
var $val2;
function __construct( $par1, $par2 )
{
$this->val1 = $par1;
$this->val2 = $par2;
}
}
$obj = new test(10, 20);
echo "Object: \n";
var_dump($obj);
// Converting object to associative array
$newArray = json_decode(json_encode($obj), true);
echo "Array: \n";
var_dump($newArray);
?>
Output:
Object:
object(test)#1 (2) {
["val1"]=> int(10)
["val2"]=> int(20)
}
Array:
array(2) {
["val1"]=> int(10)
["val2"]=> int(20)
}
Here, we have created a test class and created an object of that class. we just printed the value of the object before conversion and after conversion. You can also convert SQL query results using these methods.
Using Type Casting
In type casting, we convert the variable’s data type to another data type. Converting objects to an array using type casting is easy compared to the JSON method. This method converts using pre-defined PHP rules.
Let’s take an example to convert a PHP object into an array using type casting.
<?php
class test {
/* Member variables */
var $val1;
var $val2;
function __construct( $par1, $par2 )
{
$this->val1 = $par1;
$this->val2 = $par2;
}
}
$obj = new test(10, 20);
echo "Object: \n";
var_dump($obj);
// Converting object to associative array
$newArray = (array) $obj;
echo "Array: \n";
var_dump($newArray);
?>
Output :
Object:
object(test)#1 (2) {
["val1"]=> int(10)
["val2"]=> int(20)
}
Array:
array(2) {
["val1"]=> int(10)
["val2"]=> int(20)
}
It will produce the same output as the above example. But this time compiler will convert using type casting.
Conclusion
In this article, we have converted PHP objects into arrays using type casting and JSON functions. Those objects can be just regular class objects or SQL query result objects. It’s a very useful concept in regular logic.