Fix "Warning: Undefined array key" in PHP 8 (formerly "Undefined index")
Warning: Undefined array key "email" in /var/www/html/index.php on line 12
- Notice: Undefined index: email in /var/www/html/index.php on line 12
- Warning: Undefined array key 3 in /var/www/html/list.php on line 8
- Notice: Undefined offset: 3 in /var/www/html/list.php on line 8
- ErrorException: Undefined array key "name"
- Warning: Trying to access array offset on value of type null
You are reading $array['email'] while that key does not exist in the array. Since PHP 8.0 this is a Warning (before: the "Undefined index" notice), and Laravel turns it into an ErrorException that stops the request. Check the key with isset() or array_key_exists(), or provide a default value: $email = $_POST['email'] ?? '';.
What this error means
Reading a missing key from an array returns null, but PHP emits a warning to flag a likely bug. PHP 8.0 raised its level from E_NOTICE to E_WARNING and renamed "Undefined index" and "Undefined offset" to "Undefined array key", followed by the key ("email" for a string, 3 for an integer). Laravel and Symfony convert warnings into exceptions in their error handler: instead of showing null, the page crashes. The cousin "Trying to access array offset on value of type null" points to a different problem: the variable itself is not an array (null, false).
Common causes
- Missing form field or parameter:
$_POST['email']on the first display of the form (GET request), an unchecked checkbox (it is not sent at all),$_GET['page']with no parameter in the URL. - Structure different from what you expect: decoded JSON or an API response that does not always contain the key, or a case difference (
'Email'instead of'email'). - Numeric index out of range:
$parts[1]after anexplode()that did not find the separator, or aforloop that runs up tocount($items)inclusive. - The variable is not an array: PDO
fetch()with no row returnsfalse,json_decode()of invalid JSON returnsnull, hence "Trying to access array offset on value of type bool/null". - Migration from PHP 7 to PHP 8: old code ignored notices; now that they are warnings, they are displayed or converted into exceptions.
Step-by-step fix
-
Print the keys that are really there
The message gives the key, the file and the line. Print the array keys at that spot to see what is missing or different. In Laravel,
dd($request->all())shows everything that was sent.var_dump(array_keys($data)); // Laravel dd($request->all()); -
Provide a default value with
??The
??operator returns the right-hand value when the key does not exist or isnull, with no warning at all, even across several levels.$email = $_POST['email'] ?? ''; $page = (int) ($_GET['page'] ?? 1); $city = $user['address']['city'] ?? null; -
Choose between
isset()andarray_key_exists()isset()returnsfalsewhen the key is missing or the value isnull.array_key_exists()returnstrueas soon as the key exists, even withnull. Use the latter whennullis a legitimate value.if (isset($data['nickname'])) { echo $data['nickname']; } if (array_key_exists('deleted_at', $row)) { // key present, value may be null } -
Guard numeric indexes
After an
explode(), pad the result witharray_pad(); to loop over an array, preferforeachto aforover indexes.[$user, $domain] = array_pad(explode('@', $email, 2), 2, null); foreach ($items as $index => $item) { echo $index . ': ' . $item . PHP_EOL; } -
Check that the variable is really an array
For "Trying to access array offset on value of type…", check the function return value before indexing it.
JSON_THROW_ON_ERRORmakesjson_decode()fail loudly instead of returningnull.$data = json_decode($json, true, flags: JSON_THROW_ON_ERROR); $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row === false) { throw new RuntimeException('User not found'); } echo $row['email']; -
In Laravel: validate input and use
Arr::get()Validate the request: required keys are then guaranteed in
$validated. For a nested array,Arr::get()anddata_get()accept dot notation and a default value.use Illuminate\Support\Arr; $validated = $request->validate([ 'email' => 'required|email', 'newsletter' => 'boolean', ]); $email = $validated['email']; $newsletter = $request->boolean('newsletter'); $city = Arr::get($payload, 'address.city', 'Unknown');
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Validate every input (forms, JSON, external APIs) at the entry point, before using it in the code.
- Run PHPStan or Larastan: they report access to keys that may not exist ("Offset 'x' does not exist on array").
- Do not hide the warning with
@or by removingE_WARNINGfromerror_reporting: the bug is still there, it just becomes invisible.
Frequently asked questions
What is the difference between "Undefined index" and "Undefined array key"?
None in substance: it is the same problem. PHP 8.0 simply renamed the message and raised it from notice to warning.
Why does this warning crash my Laravel page?
Laravel converts every warning into an ErrorException. That is on purpose: access to a missing key almost always hides a bug. Fix the access instead of changing this behavior.
??, isset() or array_key_exists(): which one should I use?
?? to read a value with a default, isset() to test that a non-null value is present, array_key_exists() when the key may exist with a null value.
Useful tools for this error
More PHP & Laravel errors
- Fix "419 Page Expired" in Laravel (CSRF token mismatch)
- Fix "Allowed memory size of 134217728 bytes exhausted" in PHP
- Fix "Target class [X] does not exist" and "Class not found" in Laravel
- Fix "SQLSTATE[HY000] [2002] Connection refused" in Laravel
- Fix "No application encryption key has been specified" in Laravel
- Fix "Your requirements could not be resolved to an installable set of packages" (Composer)
- Fix "laravel.log could not be opened in append mode: Permission denied"
- Fix "Vite manifest not found at: public/build/manifest.json" in Laravel