How To Object To Array In Php

In this blog post, we will discuss two common methods of converting an object to an array in PHP. This can be useful when you are working with data that is returned as an object from an API, database, or other third-party sources and you want to convert it into an array for easier manipulation.

Method 1: Type Casting

Type casting is an easy and straightforward method to convert an object to an array in PHP. All you need to do is to use a type cast `(array)` in front of the object that you want to convert.

  $object = new stdClass();
  $object->property1 = 'Value 1';
  $object->property2 = 'Value 2';
  
  $array = (array) $object;
  

The $array variable now contains the object’s properties as an associative array:

  Array (
    [property1] => Value 1
    [property2] => Value 2
  )
  

However, this method has a limitation: it only works with public properties of the object. If your object contains private or protected properties, they will not be included in the resulting array.

Method 2: Using the json_encode() and json_decode() Functions

Another method to convert an object to an array in PHP is by using the json_encode() and json_decode() functions. This method can be used to convert both public and private properties of the object, as well as nested objects.

Here’s how you can use these functions:

  $object = new stdClass();
  $object->property1 = 'Value 1';
  $object->property2 = 'Value 2';

  $json = json_encode($object);
  $array = json_decode($json, true);
  

The $array variable now contains the object’s properties as an associative array:

  Array (
    [property1] => Value 1
    [property2] => Value 2
  )
  

When using the json_decode() function, the second parameter should be set to true to return an associative array instead of an object.

Conclusion

In this blog post, we have discussed two methods of converting an object to an array in PHP. Type casting is a simple method that works well with objects that have only public properties. If you need to convert an object with private or protected properties, or if the object contains nested objects, you can use the json_encode() and json_decode() functions.

Both methods are easy to implement and can be useful when working with data from APIs, databases, and other sources that return objects instead of arrays.