How do I fix "Undefined array key" in PHP?
Short answer
Use $_POST["name"] ?? "" instead of $_POST["name"]. The ?? operator returns the right-hand side when the key is missing or null, with no warning.
$name = $_POST['name'] ?? '';
$page = (int) ($_GET['page'] ?? 1);
$sort = $_GET['sort'] ?? 'date';Apply this to every read of $_GET, $_POST, $_SESSION and $_COOKIE. Those arrays come from the outside world and you can never assume a key is present.
#Why the key is missing
- The form field has no
nameattribute, so nothing was sent. - The checkbox was unticked — browsers do not send unchecked boxes at all.
- The request was a GET, so
$_POSTis empty. - A typo between the form and the handler.
#Assigning defaults in place
$config['timeout'] ??= 30; // set only if missing or null#isset vs empty vs array_key_exists
| True when | |
|---|---|
isset($a['k']) | The key exists and is not null |
empty($a['k']) | Missing, null, 0, "", "0", [] or false |
array_key_exists('k', $a) | The key exists, even if its value is null |