# Warning: Undefined array key / Undefined index

**Code:** `Undefined array key` · **Category:** PHP · **Seen on:** PHP

Your code reads an array key that doesn’t exist — common with `$_GET`, `$_POST` and decoded JSON.

## Meaning

PHP 8 reports “Undefined array key”; PHP 7 said “Notice: Undefined index”. It’s a warning, not fatal, but the value is `null` and often breaks logic downstream — and printed warnings can corrupt JSON or headers.

## Common causes

- Form field not submitted (unchecked checkbox, wrong name)
- Query parameter missing
- API response shape differs from expectations
- Typos in key names

## Quick fix

1. Use the null coalescing operator: `$_GET['page'] ?? 1`
2. Check with `isset()` / `array_key_exists()`
3. Validate input up front

## Detailed fix by platform

### PHP

1. Defaults with ??:

```php
$page  = (int) ($_GET['page'] ?? 1);
$email = trim($_POST['email'] ?? '');
```


## Code examples

### Reading optional input safely

```php
// ❌ Warning: Undefined array key "newsletter" when the checkbox is unchecked
$subscribe = $_POST['newsletter'];

// ✅
$subscribe = isset($_POST['newsletter']);
$page      = max(1, (int) ($_GET['page'] ?? 1));
$sort      = in_array($_GET['sort'] ?? '', ['name', 'date'], true) ? $_GET['sort'] : 'date';
```

### Nested JSON with defaults

```php
$data = json_decode($body, true) ?? [];
$city = $data['user']['address']['city'] ?? 'Unknown';   // ?? short-circuits the whole chain
```

## How to diagnose

1. **Key** — Which key and which line (from the warning)?
2. **Source** — Is the field actually sent? Check the form name / query string / JSON
3. **Shape** — var_dump() the array — is the structure what you expect?
4. **Guard** — Use ?? defaults or isset() for optional keys

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/php/undefined-array-key)
