Undefined Array Key / Offset Errors
TL;DR
Accessing a non-existent array key triggers E_WARNING (PHP 7) or is silently null (PHP 8 with nullsafe) — use isset(), array_key_exists(), or ?? to guard access.
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
✗ isset() and array_key_exists() are equivalent — isset() returns false for null values while array_key_exists() returns true. Use the right one.
Why It Matters
Silent null from undefined key propagates through calculations causing type errors or data corruption much later than the actual bug.
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
✗ Vulnerable
$config = ['debug' => true];
echo $config['database']; // Warning: Undefined array key 'database'
✓ Fixed
// 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
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
22 Mar 2026
Views
86
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 2
ChatGPT 1
ChatGPT 1
ChatGPT 56
Perplexity 10
Google 7
Amazonbot 5
Unknown AI 3
Ahrefs 1
SEMrush 1
Also referenced
How they use it
crawler 79
crawler_json 3
pre-tracking 1
Related categories
⚡
DEV INTEL
Tools & Severity
🟡 Medium
⚙ Fix effort: Low
⚡ Quick Fix
Use $arr['key'] ?? $default for simple defaults. Use array_key_exists() when null is valid. Enable E_ALL in dev to surface all undefined key warnings.
📦 Applies To
PHP 4.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
\$[a-z_]+\[
Auto-detectable:
✓ Yes
phpstan
psalm
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✓ Auto-fixable
Fix: Low
Context: Line
CWE-476