Undefined variable 🐘 PHP

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

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