PHP error guide

PHP "Trying to access array offset on null": Diagnosis and Fixes

Error summary

You used `$value[...]` when `$value` is null (or another non-array). Fix the upstream lookup that returned null before indexing, or guard with type checks.

What it means

You used $value[...] when $value is null (or another non-array). Fix the upstream lookup that returned null before indexing, or guard with type checks.

What the error means

Array offset access requires an array (or ArrayAccess in some cases). Null means the previous call did not return a structure—often a missing DB row, failed decode, or optional nested key.

Why PHP produces it

PHP 7.4+ tightened illegal offset access warnings so null/bool/int/string misuse is visible instead of producing surprising nulls later.

PHP version notes

Related warnings exist for offset access on bool/int/string—see sibling pages for those exact messages.

Most common causes

  • Function returned null instead of an array
  • Chaining $data['user']['email'] when $data['user'] is null
  • json_decode() failed and returned null
  • Optional relationship missing in a query result

Minimal examples

BAD — reproduces the problem

php
$row = $stmt->fetch(PDO::FETCH_ASSOC); // false/null when no row\n$name = $row['name'];

FIXED — safer pattern

php
$row = $stmt->fetch(PDO::FETCH_ASSOC);\nif ($row === false) {\n    throw new RuntimeException('User not found');\n}\n$name = $row['name'];

Step-by-step diagnosis

  1. Identify the expression before [...] on the reported line.
  2. Log gettype() / var_export() of that value in development only.
  3. Check the function that produced it for failure paths.
  4. Confirm whether null is a valid business state.

Fixes

Fix #1: Guard before indexing

Check for array type (or non-null) before reading offsets.

php
$profile = fetchProfile($id);\nif (!is_array($profile)) {\n    throw new RuntimeException('Profile not found');\n}\n$email = $profile['email'] ?? null;

Fix #2: Nullsafe nested reads with defaults

Break nested access into guarded steps or use null coalescing carefully.

php
$user = $data['user'] ?? null;\n$email = is_array($user) ? ($user['email'] ?? null) : null;

Common mistakes when fixing it

  • Casting null to array with (array) null which yields an empty array and hides the bug
  • Ignoring json_last_error() after decode

How to prevent it

  • Return typed results or Result objects from finders
  • Enable strict development error reporting
  • Add tests for empty result sets

Web server / environment notes

Any PHP SAPI where failed lookups return null/false

Tags: cli,fpm,linux

Categories

Relevant ZendStudio.net tools