Undefined Array Key / Offset Errors
debt(d5/e1/b2/t5)
Closest to 'specialist tool catches' (d5), phpstan/psalm detect undefined offset access in static analysis; PHP itself only emits a warning at runtime that's easy to miss in production logs.
Closest to 'one-line patch' (e1), quick_fix is to swap $arr['key'] for $arr['key'] ?? $default — a single-call replacement at each site.
Closest to 'minimal commitment' (b1), slightly above because the pattern recurs across web/cli/queue contexts but each occurrence is local and imposes no structural commitment.
Closest to 'notable trap' (t5), the misconception that isset() and array_key_exists() are equivalent is a documented gotcha most PHP devs eventually learn; silent null propagation also surprises beginners.
TL;DR
Explanation
PHP 7 emits E_NOTICE for undefined offset. PHP 8 emits E_WARNING. Neither throws — the expression evaluates to null. Undefined index means string key missing, undefined offset means integer key missing. Best practices: use isset($arr['key']) to check existence, $arr['key'] ?? 'default' for null-coalescing default, array_key_exists() when null is a valid value (isset() returns false for null values). In typed contexts (PHP 8), use dedicated data structures or value objects instead of raw arrays to prevent key access errors.
Common Misconception
Why It Matters
Common Mistakes
- Using $arr['key'] without isset() check — produces warning and null.
- Confusing isset() with array_key_exists() when null is a valid array value.
- Not enabling E_WARNING in development — errors become invisible.
Code Examples
$config = ['debug' => true];
echo $config['database']; // Warning: Undefined array key 'database'
// Null coalescing:
$db = $config['database'] ?? 'mysql://localhost/app';
// When null is a valid value:
if (array_key_exists('database', $config)) {
$db = $config['database']; // could be null
}
// PHP 8.1+ — first-class enums/value objects are better than raw arrays