Skip to content

/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
<?php
$user = ['id' => 7];
echo $user['name'];          // Warning: Undefined array key "name"
echo $_GET['page'];          // same warning when ?page= is not in the URL

In 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
<?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

ExpressionMissing keyKey with null value
$a['k']Warning, evaluates to nullnull, no warning
$a['k'] ?? 'x''x', no warning'x'
isset($a['k'])falsefalse
array_key_exists('k', $a)falsetrue
empty($a['k'])true, no warningtrue

Sources