Sometimes working with PHP we need to convert object into array for implement array function or reduce looping from our code. Here, we will see two methods to convert object into associative array.
Before starting let's understand what is object in PHP. An object is an instance of a class which 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
Both methods works into similar way. In type casting, we can convert type of variable into another type. While in JSON method, first we convert object into JSON and then we convert JSON into array.
Here first of all, we will convert object into JSON string and then convert JSON string in associative array. We will use json_encode() and json_decode() functions. Below is syntax for converting object to array using JSON function:
Let's take prectial example for it.
Here, we have created test class and create object of that class. we just printed value of object before conversion and after conversion. You can also convert SQL query result using these methods.
In type casting, we convert variable's data type to another data type. Converting object to array using type casting is easy compare to JSON method. This method converts using per-defined PHP rules.
Let's take example to convert PHP object into array using type casting.
It will produce same output as above example. But this time compiler will convert using type casting.
In this article, we have converted PHP object into array using type casting and JSON functions. Those object can be just regular class object or SQL query result object. It's very useful concept in regular logic.
Ask anything about this examples