Cannot Use Object as Array

Fatal error: Uncaught Error: Cannot use object of type stdClass as array

Quick Answer

You are using array syntax on an object. Access object properties with the arrow operator -> instead of bracket notation, or cast the object to an array.

Why This Happens

PHP distinguishes between arrays and objects. When you receive an object, such as from json_decode() without the associative flag or from a database query returning objects, you cannot access its properties with square brackets unless the class implements ArrayAccess.

The Problem

$data = json_decode('{"name": "Alice"}');
echo $data['name']; // Error: stdClass is not an array

The Fix

// Option 1: Access as object property
$data = json_decode('{"name": "Alice"}');
echo $data->name;

// Option 2: Decode as associative array
$data = json_decode('{"name": "Alice"}', true);
echo $data['name'];

Step-by-Step Fix

  1. 1

    Check the variable type

    Use var_dump() or gettype() to confirm the variable is an object rather than an array.

  2. 2

    Determine the data source

    Check if the data comes from json_decode, a database query, or an API response that returns objects by default.

  3. 3

    Use the correct access syntax

    Switch to -> for object property access, or pass true as the second argument to json_decode to get an associative array.

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free