Warning: Undefined array key / Undefined index
Your code reads an array key that doesn’t exist — common with $_GET, $_POST and decoded JSON.
Seen on:
PHP
Meaning
PHP 8 reports “Undefined array key”; PHP 7 said “Notice: Undefined index”. It’s a warning, not fatal, but the value is null and often breaks logic downstream — and printed warnings can corrupt JSON or headers.
Common causes
- Form field not submitted (unchecked checkbox, wrong name)
- Query parameter missing
- API response shape differs from expectations
- Typos in key names
⚡ Quick fix
- Use the null coalescing operator:
$_GET['page'] ?? 1 - Check with
isset()/array_key_exists() - Validate input up front
Detailed fix by platform
PHP
- Defaults with ??:php
$page = (int) ($_GET['page'] ?? 1); $email = trim($_POST['email'] ?? '');
Code examples
Reading optional input safely
php
// ❌ Warning: Undefined array key "newsletter" when the checkbox is unchecked
$subscribe = $_POST['newsletter'];
// ✅
$subscribe = isset($_POST['newsletter']);
$page = max(1, (int) ($_GET['page'] ?? 1));
$sort = in_array($_GET['sort'] ?? '', ['name', 'date'], true) ? $_GET['sort'] : 'date';Nested JSON with defaults
php
$data = json_decode($body, true) ?? [];
$city = $data['user']['address']['city'] ?? 'Unknown'; // ?? short-circuits the whole chainHow to diagnose
- Key — Which key and which line (from the warning)?
- Source — Is the field actually sent? Check the form name / query string / JSON
- Shape — var_dump() the array — is the structure what you expect?
- Guard — Use ?? defaults or isset() for optional keys
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026