/errors/php/undefined-array-key
PHP Warning: Undefined array key "name"
The commands on this page have not been executed by our verification runner yet.updated
- tool
- PHP
- exit code
- 0
- versions
- PHP 8.0+ (Warning: Undefined array key), PHP 7.x (Notice: Undefined index)
- os
- any
Warning: Undefined array key "name" in /path/to/file.php on line N means the code read $array["name"] but the array has no such key. PHP continues and uses null as the value, so the script may still work, but the warning is shown and logged. Give the read a default with the null coalescing operator ($_POST['name'] ?? ''), or check with isset() / array_key_exists() first. With a numeric key the message is Undefined array key 3.
Example
<?php
$user = ['id' => 7];
echo $user['name']; // Warning: Undefined array key "name"
echo $_GET['page']; // same warning when ?page= is not in the URLIn PHP 7 the same code produced Notice: Undefined index: name (and Notice: Undefined offset: 3 for lists). PHP 8.0 renamed the message and raised its level from notice to warning, so pages that looked clean on PHP 7 start printing it after an upgrade.
Fixes
<?php
$name = $user['name'] ?? 'anonymous'; // default when the key is missing or null
$page = (int) ($_GET['page'] ?? 1);
if (isset($user['email'])) { // false for missing keys and for null values
send($user['email']);
}
if (array_key_exists('nickname', $user)) { // true even when the value is null
echo 'nickname set';
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // read form fields only after a submit
$title = trim($_POST['title'] ?? '');
}Checks compared
| Expression | Missing key | Key with null value |
|---|---|---|
| $a['k'] | Warning, evaluates to null | null, no warning |
| $a['k'] ?? 'x' | 'x', no warning | 'x' |
| isset($a['k']) | false | false |
| array_key_exists('k', $a) | false | true |
| empty($a['k']) | true, no warning | true |
Sources
Related pages
errors · phpPHP Fatal error: Uncaught Error: Call to undefined functionPHP throws Call to undefined function when a function is not defined or its extension (mbstring, curl, mysqli) is not loaded. Check php -m and includes.errors · phpPHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate N bytes)PHP hit memory_limit: 134217728 bytes is the 128M default. Process data in chunks or generators, or raise memory_limit in php.ini, with ini_set or with -d.compare · phpPHP include vs require vs require_once: what is the difference?PHP include warns and continues when the file is missing, require stops with a fatal error, and the _once variants skip files already loaded. When to use each.