Skip to content
CoursesWeb Forum

How do I convert a stdClass object to an array in PHP?

Staff answerWritten by Callum Iwu · PHP Forms, Sessions and Basics0 replies

Short answer

Cast it with (array) $obj to get an array of its properties. That only converts the top level, so nested objects stay objects. If the object came from json_decode(), skip the conversion and pass true as the second argument, which returns associative arrays all the way down. Use whichever matches where the object came from.

Written by Callum Iwu · Moderator: PHP, MySQL, Node.js and AI coding tools ·
CiteCoursesWeb Forum, "How do I convert a stdClass object to an array in PHP?", https://coursesweb.net/forum/t/how-do-i-convert-a-stdclass-object-to-an-array-in-php/, accessed 2026-11-20.
  1. Moderator: PHP, MySQL, Node.js and AI coding tools ·

    Where stdClass objects come from

    stdClass is PHP's empty, built-in class. You meet it in three places: json_decode() without its second argument, a database row fetched as an object (for example fetch_object() in mysqli), and any time you cast a value to an object with (object). The PHP manual on objects says that converting a value of another type to an object creates a new instance of stdClass, and that an array becomes an object with properties named by its keys.

    The problem shows up when you try to read it like an array: $data['name'] fails on an object, because objects use arrow syntax, $data->name. Both are valid, but they belong to different types.

    Working example

    <?php
    $json = '{"name":"Ada","tags":["php","sql"],"address":{"city":"Lyon"}}';
    
    // Option 1: decode straight to arrays (best when the data starts as JSON)
    $data = json_decode($json, true);
    echo $data['address']['city'];        // Lyon
    
    // Option 2: you already have an object, so cast it
    $obj = json_decode($json);            // stdClass
    $arr = (array) $obj;
    echo $arr['name'];                    // Ada
    var_dump($arr['address']);            // still an object: only the top level changed
    
    // Option 3: you already have an object and need every level as arrays
    $deep = json_decode(json_encode($obj), true);
    echo $deep['address']['city'];        // Lyon
    

    The json_decode manual describes the associative parameter: when it is true, JSON objects are returned as associative arrays, and when it is false, as objects.

    Why it works

    An array cast reads the object's properties and builds an array with the property names as keys. It does not look inside the values, so a property holding another object keeps holding that object. Option 3 round trips the data through a JSON string: json_encode() turns every level into JSON text, and json_decode(..., true) builds arrays from it. It is a handy trick for plain data and a poor one for objects that hold anything JSON cannot represent, such as open file handles.

    Which option to choose

    Situation Use
    Data starts as a JSON string json_decode($json, true)
    One flat object, one level only (array) $obj
    Nested object, every level needed json_decode(json_encode($obj), true)
    Row from your own database query Fetch it as an array in the first place

    Mistakes beginners make

    1. Mixing the two syntaxes. After (array) $obj, write $arr['name'], not $arr->name. After json_decode($json) with no second argument, write $obj->name.
    2. Expecting the cast to be recursive. In the example above, $arr['address'] is still a stdClass. Writing $arr['address']['city'] there gives an error.
    3. Hyphens in property names. A JSON key such as foo-bar is fine as an array key, but as an object property it needs braces and quotes: $obj->{'foo-bar'}. The json_decode manual shows this form. Arrays avoid the issue.
    4. Not checking for null. The manual says json_decode() returns null when the string cannot be decoded. JSON needs double quotes around names and strings and does not allow trailing commas, so JavaScript-style text often fails.

    Check this in order

    1. Print the value with var_dump($data). Does it say object(stdClass) or array? That tells you which syntax to use.
    2. If it is NULL, call json_last_error_msg() straight after the decode to see why.
    3. Decide once, at the point of decoding, whether your code works with arrays or objects, and stay with that.
    4. If the data comes from a database, see How do I use prepared statements with mysqli or PDO in PHP? and fetch rows as associative arrays instead of converting them later.
    5. If you are reading submitted form fields, see How do I handle GET and POST form data safely in PHP?, since those arrive as arrays already.

    Our CoursesWeb page on common PHP errors and solutions covers other messages you will meet along the way.

    0
    ReplyLink

Plain text or simple Markdown. Links are nofollow. Your email is never shown.

CoursesWeb Forum. Questions and answers on learning web development: HTML, CSS, JavaScript, PHP, MySQL, Node.js and AI coding help.