Warning: Undefined variable $x
PHP read a variable that was never assigned in the current scope.
Undefined variableNotice: Undefined variable 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
$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 not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
Most viewed in PHP
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 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.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 13 Oct 2026