Warning: Undefined variable $x
PHP read a variable that was never assigned in the current scope.
Seen on:
PHP
Meaning
In PHP 8 reading an unset variable raises a warning (a notice in PHP 7) and the value is treated as null. Functions have their own scope, so variables from outside are not visible unless passed in, captured with use, or declared global.
Common causes
- Typo in the variable name
- Variable only set inside an if branch that didn’t run
- Using an outer variable inside a function or closure without
use - Template expecting a variable the controller never passed
⚡ Quick fix
- Initialise the variable before any branch
- Pass values into functions as parameters
- Capture outer variables in closures with
use ($var)or arrow functions - Use
$x ?? 'default'for optional values
Detailed fix by platform
PHP
- Turn on
error_reporting(E_ALL)in development so every undefined variable is visible - Run a static analyser (PHPStan/Psalm) to catch them before runtime
Code examples
Closure scope
php
$discount = 0.1;
$prices = array_map(function ($p) { return $p * (1 - $discount); }, $prices); // ❌ undefined
$prices = array_map(fn($p) => $p * (1 - $discount), $prices); // ✅ arrow fn capturesHow to diagnose
- Name — Is the spelling identical?
- Scope — Is it defined in this function?
- Flow — Is it assigned on every path?
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 2 Oct 2026