Error Reference › PHP
PHP
Undefined variable / array key (PHP)
You read a variable or array key that was never set.
What it looks like
Warning: Undefined variable $total in /var/www/app/cart.php on line 31
Warning: Undefined array key "page" in /var/www/app/list.php on line 8
What does "Undefined variable / array key (PHP)" mean?
Raised as a warning since PHP 8 (older versions called it a notice). The script keeps running with null in place of the value, which can cause wrong output further on even when the warning itself is hidden.
What causes "Undefined variable / array key (PHP)"?
- A typo in the variable/key name.
- Assuming a request/array key always exists.
- A variable defined only inside an if/loop branch.
How do I confirm the cause?
- For a variable, check it is assigned on every path — a variable set only inside an if or a loop is undefined when that code is skipped.
- For an array key, check where the array comes from; request data ($_GET, $_POST) never guarantees a key is present.
- Look for a typo between where it is set and where it is read ($totals vs $total).
How do I fix "Undefined variable / array key (PHP)"?
- Check the name and that it's set on all paths.
- Use isset()/?? defaults for request data ($_GET['x'] ?? '').
- Initialize the variable before the branch.
How do I stop it happening again?
- Initialise variables before conditional blocks, and read optional keys with ?? defaults ($_GET['page'] ?? 1).
- Show warnings in development (error_reporting(E_ALL)) so they are caught before release.