PHP array to object


Answers ( 1 )


    It concerns the conversion of an array into an object in the PHP programming language.

    To convert an array to an object in PHP, you can use the (object) casting operator or the json_decode and json_encode functions. Here are the methods:

    Method 1: Using (object) Casting

    This method directly casts the array to an object. It's the simplest way to convert an associative array to an object.

    $array = ['key1' => 'value1', 'key2' => 'value2'];
    $object = (object) $array;

    After this, $object will be an instance of stdClass, and you can access the values like $object->key1.

    Method 2: Using json_decode and json_encode

    This method first converts the array to JSON, then decodes the JSON into an object. It's a bit more roundabout but is useful in certain scenarios, especially when dealing with nested arrays.

    $array = ['key1' => 'value1', 'key2' => 'value2'];
    $json = json_encode($array);
    $object = json_decode($json);

    With this method, $object will also be an instance of stdClass with the same properties.


    • When converting arrays to objects, associative arrays (arrays with string keys) are most suitable since their keys can directly map to object properties.
    • For indexed arrays (arrays with numeric keys), the conversion will still work, but accessing the elements will be less intuitive since numeric properties are not standard in PHP objects.
    • Be mindful of the depth of the array. Deeply nested arrays might require recursive conversion if you need all levels to be objects.

    These are the primary ways to convert an array to an object in PHP. Choose the method that best fits your specific use case.

Leave an answer