"Undefined variable $x" in PHP — What It Means and How to Fix It

What the PHP error "Undefined variable $x" means and how to fix it.

Published October 30, 2026

PHP raises 'Undefined variable' when code reads a variable that was never assigned in the current scope. In PHP 8 it is a warning; the value is treated as null.

What it means and why it happens

Typical causes: a typo in the name, using a variable inside a function that was defined outside (functions have their own scope), or a variable assigned only inside an if branch that did not run.

Read the full message: it names the file and line where the problem was detected, which is the best place to start.

What you see

run the code
Warning: Undefined variable $x in index.php on line 5

Practical examples

Code that triggers it

<?php
function total() {
    return $price * 2;   // $price is not in this scope
}
$price = 10;
echo total();

The fix

<?php
function total(float $price) {
    return $price * 2;
}
$price = 10;
echo total($price);

Initialise defaults

$name = $_POST['name'] ?? '';   // null coalescing avoids the warning
$items = [];                    // initialise before loops

Common mistakes

  • Expecting global variables inside functions without passing them or using global.
  • Typos such as $usre vs $user.
  • Reading a variable only assigned in a branch.

Key takeaways

  • Undefined variable: PHP raises 'Undefined variable' when code reads a variable that was never assigned in the current scope.
  • Read the message and the line number first.
  • Fix the cause, don't just silence the error.

FAQ

Is it an error or a warning?

A warning in PHP 8 (a notice before), but it hides real bugs so fix it.

How do I find which line caused Undefined variable?

The error message and stack trace show the file and line; start there and work backwards.

More PHP articles