Warning: Undefined variable and Undefined array key in PHP
Warning: Undefined variable $total in /var/www/app/cart.php on line 12Short answer
PHP read a variable or array key that was never set. In PHP 8 this is a Warning, and the old Undefined index and Undefined offset messages became Undefined array key. The value read is null and the script continues. Set the variable on every path, or read the key with isset() or the ?? operator.
Fix it fast
1Find out which cause you have
Read the message: it names the variable or key and the file and line. Open that line and see where the value should have been set.
php -l form.php grep -n "email" form.php2Match what you see, then jump to its fix
- 1
Warning: Undefined variable $nameA variable is set only on some code pathsFix - 2
Warning: Undefined array key "email" (the key can be a string or a number)An array key is read that the array does not haveFix - 3
The code worked on PHP 7.4, and the same line now prints Warning instead of NoticeUpgrading to PHP 8 turned a hidden notice into a visible warningFix
- 1
What does the error look like?
Warning: Undefined variable $total in /var/www/app/cart.php on line 12Warning: Undefined array key "email" in /var/www/app/form.php on line 8Warning: Undefined array key 3Notice: Undefined index: email (PHP 7 and older)
Cause 1 of 3
A variable is set only on some code paths
1Check
Look for a variable assigned inside an if, a loop or a try, and then read after it. If the branch did not run, the variable does not exist.
grep -n -B3 -A3 "\$total" cart.php2Fix
Give the variable a default before the branch. Appending with [] to an undefined variable is the one case that does not warn, because PHP creates the array.
<?php
$total = 0;
foreach ($items as $item) {
$total += $item['price'];
}
echo $total;3Verify
Run the page through a path that skips the branch and see no warning.
php cart.phpConfirmed by php.net
Cause 2 of 3
An array key is read that the array does not have
1Check
Typical sources are $_POST, $_GET and rows from a query. A form field that was not submitted, or a column that was not selected, is not in the array.
php -r "var_dump(\$_POST[\"email\"] ?? null);"2Fix
Use the null coalescing operator for a default, or isset() when you need to branch. Do not use @ to hide it.
<?php
$email = $_POST['email'] ?? '';
if (isset($_POST['agree'])) {
// checkbox was ticked
}3Verify
Submit the form without the field and confirm no warning appears.
php -l form.phpConfirmed by php.net
Cause 3 of 3
Upgrading to PHP 8 turned a hidden notice into a visible warning
1Check
Before PHP 8.0 these were notices and error_reporting often hid them. In PHP 8 they are warnings and the message text changed: Undefined index and Undefined offset became Undefined array key.
php -v
php -i | grep -E "^error_reporting "2Fix
Fix each place with the two patterns above. Raising the display level is not a fix: on production keep display_errors off and log the warnings, then clean the log up.
; php.ini (production)
display_errors = Off
log_errors = On3Verify
Run the test suite or key pages and check the PHP log is free of Undefined array key lines.
grep -c "Undefined array key" /var/log/php/error.logConfirmed by php.net
How do I stop it coming back?
- Initialise variables at the top of the function or file, before any if or loop.
- Read request input only through ?? or isset(), with a safe default.
- Run the test suite with error_reporting = E_ALL so warnings fail early.
- Use a static analyser such as PHPStan to find undefined variables before deploy.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
Related fixes
Back end
PHP shows a blank page and no error message
No Warning or Fatal error text, even though the script is broken
A blank page means PHP hit an error but was told not to print it.
4 causes, each with a fixBack end
Android gets HTML instead of JSON from a PHP API
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
The response body is not JSON.
2 causes, each with a fixBack end
Apache returns 403 when a URL contains %3F
a request like /page%3Fname=test is refused while /page?name=test works
Recent Apache httpd blocks a rewrite when the request contains an encoded question mark (%3F) and the rewritten target has a literal ?.
2 causes, each with a fixBack end
Apache returns 500 with Premature end of script headers
500 Internal Server Error
Apache ran your script, but the script printed no valid HTTP header before its output.
3 causes, each with a fixBack end
Apache returns 503 or 504 because PHP-FPM did not answer in time
Error dispatching request
Apache sent the request to PHP-FPM and gave up waiting.
3 causes, each with a fixBack end
AWS SDK for PHP cannot get credentials from the instance profile metadata server
Error retrieving credentials from the instance profile metadata server.
The SDK tries the EC2 instance metadata service when it has no valid credentials from anywhere earlier in its chain.
4 causes, each with a fix