Undefined variable PHP Origin: Application & API Last updated 13 Oct 2026

Warning: Undefined variable $x

PHP read a variable that was never assigned in the current scope.

Exact message you may see Undefined variableNotice: Undefined variable
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

  1. Initialise the variable before any branch
  2. Pass values into functions as parameters
  3. Capture outer variables in closures with use ($var) or arrow functions
  4. Use $x ?? 'default' for optional values

Detailed fix by platform

PHP

  1. Turn on error_reporting(E_ALL) in development so every undefined variable is visible
  2. 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 captures

How to diagnose

  1. Name — Is the spelling identical?
  2. Scope — Is it defined in this function?
  3. 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:

Where this error sits

Origin: Application & API. Errors that are often confused with or caused by this one (click to open):

Array offset on null — Warning: Trying to access array offset on value of type null (PHP)Array offset on nullArray to string conversion — Warning: Array to string conversion (PHP)Array to string conve…Object.keys null — TypeError: Cannot convert undefined or null to object (JavaScript)Object.keys nullreading length — TypeError: Cannot read properties of undefined (reading 'length') (JavaScript)reading lengthTypeError — TypeError: Cannot read properties of undefined (reading 'x') (JavaScript)TypeErrorTypeError set undefined — TypeError: Cannot set properties of undefined (setting 'x') (JavaScript)TypeError set undefin…Undefined property — Warning: Undefined property: Class::$prop (PHP)Undefined propertyUndefined…

Explore the map of this error Full error map →

🧠 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.