Ffile2fix
Sign in Get started

How to fix "Cannot use object of type stdClass as array"

Fatal error: Uncaught Error: Cannot use object of type stdClass as array in /home/user/public_html/api.php:23

The variable holds an object, but the code reads it with array brackets like $data['name']. Objects use $data->name, so either change the syntax or make the data an array in the first place.

Also appears as: Cannot use object of type WP_Post as array · Cannot use object of type Illuminate\Support\Collection as array · Cannot use object of type App\Models\User as array

Common causes

  • json_decode($json) without the second argument returns stdClass objects, not arrays
  • Database results fetched as objects ($wpdb->get_results() default OBJECT, PDO::FETCH_OBJ, mysqli fetch_object())
  • WordPress functions returning objects such as WP_Post, WP_User or WP_Term
  • API client libraries returning response objects
  • Mixing code written for arrays with a library that changed to returning objects

How to fix it

  1. Check what the variable is. var_dump($data) or get_debug_type($data) to confirm it is an object and see its property names.
  2. Use object syntax. Change $data['name'] to $data->name, and nested $data['user']['email'] to $data->user->email.
  3. Decode JSON as arrays. If the rest of the code expects arrays, use json_decode($json, true) so you get associative arrays throughout.
  4. Choose the fetch mode. WordPress: $wpdb->get_results($sql, ARRAY_A). PDO: $stmt->fetch(PDO::FETCH_ASSOC). mysqli: fetch_assoc() instead of fetch_object().
  5. Convert only when needed. (array) $obj works for flat stdClass objects; for nested ones use json_decode(json_encode($obj), true). Avoid this on large data in hot paths.
  6. For framework objects, use their API. Laravel collections support ->toArray(), ->get('key') and array access on some types; Eloquent models expose attributes via ->name or ->toArray().

PHP

$obj = json_decode($json);        // stdClass
echo $obj->user->email;

$arr = json_decode($json, true);  // array
echo $arr['user']['email'];

$rows = $wpdb->get_results($sql, ARRAY_A); // WordPress

How to stop it happening again

  • Pick arrays or objects for a dataset and stick to it
  • Always pass true to json_decode() when you want arrays
  • Set the database fetch mode explicitly

Frequently asked questions

Why does json_decode return an object?

By default it maps JSON objects to stdClass. Pass true as the second argument (or the JSON_OBJECT_AS_ARRAY flag) to get associative arrays.

Is casting with (array) safe?

For simple stdClass objects yes, but it only converts the top level, and private or protected properties of other classes get mangled key names.

What is the reverse error?

'Attempt to read property "name" on array' means you used -> on an array. Switch to $data['name'] or decode without true.