Sling Academy
Home/PHP/PHP: How to convert an array to an object and vice versa

PHP: How to convert an array to an object and vice versa

Last updated: January 10, 2024

Overview

In PHP, arrays and objects are two fundamental types for storing data. Both have their unique features and use-cases. Understanding how to convert between arrays and objects is essential for developers to manipulate data effectively within their applications. This tutorial will guide you through the process of transforming arrays into objects and vice versa using various methods, accompanied by illustrative examples and scenarios.

Converting an Array to an Object

Converting an array to an object in PHP can be done using the (object) casting operator or the json_encode() and json_decode() functions. This conversion is useful when you want to utilize object syntax to access array elements or if a function specifically requires an object as a parameter.

Using Object Casting

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

$object = (object) $array;

// Accessing properties
echo $object->name;  // Outputs: John

Using JSON Functions

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

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

// Accessing properties
echo $object->name;  // Outputs: John

Using stdClass

$array = array(
    'name' => 'John',
    'age' => 30,
    'email' => '[email protected]'
);

$object = new stdClass();
foreach ($array as $key => $value) {
    $object->{$key} = $value;
}

// Accessing properties
echo $object->name;  // Outputs: John

Converting an Object to an Array

Objects can be converted to arrays using the (array) casting operator or the get_object_vars() function. This can be necessary when you want to work with array functions or require an associative array representation of an object’s properties.

Using Array Casting

$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$object->email = '[email protected]';

$array = (array) $object;

// Accessing values
echo $array['name'];  // Outputs: John

Using get_object_vars()

$object = new stdClass();
$object->name = 'John';
$object->age = 30;
$object->email = '[email protected]';

$array = get_object_vars($object);

// Accessing values
echo $array['name'];  // Outputs: John

Advanced Examples

In more complex scenarios, objects and arrays may contain nested structures. Converting such data may require a recursive approach to ensure the integrity of the conversions.

Recursive Conversion from Array to Object

function arrayToObjectRecursive($array) {
    $object = new stdClass();
    foreach ($array as $key => $value) {
        $object->{$key} = is_array($value) ? arrayToObjectRecursive($value) : $value;
    }
    return $object;
}

$nestedArray = array(
    'name' => 'John',
    'age' => 30,
    'contacts' => array(
        'email' => '[email protected]',
        'phone' => '1234567890'
    )
);

$nestedObject = arrayToObjectRecursive($nestedArray);

Recursive Conversion from Object to Array

function objectToArrayRecursive($object) {
    $array = is_object($object) ? get_object_vars($object) : $object;
    foreach ($array as $key => $value) {
        $array[$key] = (is_array($value) || is_object($value)) ? objectToArrayRecursive($value) : $value;
    }
    return $array;
}

$nestedObject = new stdClass();
$nestedObject->name = 'John';
$nestedObject->age = 30;
$nestedObject->contacts = new stdClass();
$nestedObject->contacts->email = '[email protected]';
$nestedObject->contacts->phone = '1234567890';

$nestedArray = objectToArrayRecursive($nestedObject);

Handling Special Cases

Objects that implement the ArrayAccess interface behave like arrays but are objects underneath. Certain functions may require explicit conversion depending on their interface expectations.

ArrayAccess Objects

class ArrayObjectExample implements ArrayAccess {
    private $container = array();
    // ArrayAccess methods implementation
    // ...
}

$obj = new ArrayObjectExample();
// Add some data to the object
$obj['name'] = 'John';

// Convert to an array
$array = iterator_to_array($obj);

Conclusion

This tutorial walked you through different techniques to convert arrays to objects and objects to arrays in PHP. Whether you choose the simplicity of casting, the flexibility of JSON functions, or require advanced recursion, PHP offers versatile methods for data structure manipulation. Keep these tools at hand to seamlessly adapt your data to the needs of your application.

Next Article: PHP: How to sort an array of objects by property values

Previous Article: PHP: How to remove the first/last element from an array

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array