Sometimes working with PHP we need to convert objects into array for implement array function 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 object to array in PHP
- Using json_encode and json_decode
- Using type casting
Both methods work similarly. In type casting, we can convert type of variable into another type. While in JSON method, first we convert objects into JSON and then we convert JSON into array.
Using json_encode and json_decode
Here, we will convert an object into 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 JSON function:
Let's take a practical example of it.
Here, we have created a test class and created an object of that class. we just printed value of object before conversion and after conversion. You can also convert SQL query results using these methods.
Using Type Casting
In type casting, we convert variable's data type to another data type. Converting objects to array using type casting is easy compared to 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.
Output :
It will produce the same output as above example. But this time compiler will convert using type casting.
Conclusion
In this article, we have converted PHP objects into array using type casting and JSON functions. Those objects can be just regular class object or SQL query result object. It's very useful concept in regular logic.