Convert PHP object into associative array

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

  1. Using json_encode and json_decode
  2. Using type casting

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.

Using json_encode and json_decode

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.

Output :

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.

Using Type Casting

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.

Output :

It will produce same output as above example. But this time compiler will convert using type casting.

Conclusion

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.


Share your thoughts

Ask anything about this examples