php

Converting Object Data to Array

PHP provides several methods to convert object data into an array. 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