How do I fix "Undefined array key" in PHP?

PHP & the Web 2 min read Full lesson: Building a PHP Web Form
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.

php
$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 name attribute, so nothing was sent.
  • The checkbox was unticked — browsers do not send unchecked boxes at all.
  • The request was a GET, so $_POST is empty.
  • A typo between the form and the handler.

#Assigning defaults in place

php
$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