php

Converting Object Data to Array

PHP provides several methods to convert object data into an array. you often come across the need to convert object data into an array for various operations like data manipulation or formatting. In this post, we’ll walk through several methods to achieve this conversion, along with explanations to help you choose the right approach for your project. Here are a few ways to accomplish this:

Using Type Casting

Type casting an object to an array is a simple and direct approach:

// Define a sample class
class Sample {
    public $property1 = 'Value 1';
    public $property2 = 'Value 2';
}

// Create an instance of the class
$object = new Sample();

// Convert object to an array using type casting
$array = (array) $object;

// Output the resulting array
var_dump($array);

Using get_object_vars()

The get_object_vars() function retrieves all the properties of an object as an associative array:

// Define a sample class
class Sample {
    public $property1 = 'Value 1';
    public $property2 = 'Value 2';
}

// Create an instance of the class
$object = new Sample();

// Convert object properties to an array using get_object_vars()
$array = get_object_vars($object);

// Output the resulting array
var_dump($array);

Using JSON Serialization

Another method involves converting the object to JSON format and then decoding it back to an associative array:

// Define a sample class
class Sample {
    public $property1 = 'Value 1';
    public $property2 = 'Value 2';
}

// Create an instance of the class
$object = new Sample();

// Convert object to array using JSON
$array = json_decode(json_encode($object), true);

// Output the resulting array
var_dump($array);

Note:

  • When type casting or using get_object_vars(), only public properties will be converted to an array. Private and protected properties won’t be accessible.
  • Using JSON serialization might not be efficient for complex nested objects or objects containing non-serializable data types.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button