Ffile2fix
Sign in Get started

How to fix "Warning: Undefined variable" in PHP

Warning: Undefined variable $total in /home/user/public_html/cart.php on line 37

Your code read a variable that has no value in the current scope. PHP 8 raised this from a notice to a warning. The usual cause is a variable that is only set inside an if block, or one defined outside a function and used inside it.

Also appears as: Notice: Undefined variable: total (PHP 7 wording) · Warning: Undefined variable $post in /home/user/public_html/wp-content/themes/mytheme/template-parts/card.php · Warning: Undefined variable $this (in a static method)

Common causes

  • The variable is only assigned inside an if, loop or try block that did not run
  • A function uses a variable from outside without passing it as a parameter
  • A closure uses an outer variable without a use ($var) clause
  • A typo or case difference ($Total vs $total)
  • Template files expecting variables that the caller did not pass
  • Old code relying on register_globals, which was removed long ago

How to fix it

  1. Initialise the variable first. Set a default before any condition, for example $total = 0; at the top. Then the variable exists whichever branch runs.
  2. Pass values into functions. Functions in PHP cannot see outer variables. Add a parameter, such as function render($total), and pass the value when calling it.
  3. Add use() to closures. For anonymous functions write function () use ($total) { ... }, or use an arrow function fn() => $total * 2, which captures outer variables automatically.
  4. Check spelling and case. Variable names are case-sensitive. Search the file for the name to confirm it is spelled the same everywhere.
  5. Pass data to templates explicitly. In WordPress use get_template_part('card', null, ['post' => $post]) and read $args['post'] inside the template, rather than expecting a variable to exist.

Initialise before conditions and capture in closures

$total = 0;
foreach ($items as $item) {
    $total += $item['price'];
}

$withTax = array_map(fn($p) => $p * $rate, $prices);
$log = function ($msg) use ($logger) { $logger->info($msg); };

How to stop it happening again

  • Declare variables with defaults at the top of each block
  • Avoid global variables; pass data as parameters
  • Use a static analyser such as PHPStan to catch undefined variables
  • Develop with error_reporting(E_ALL) and display_errors on

Frequently asked questions

Why did this appear after upgrading to PHP 8?

PHP 8 changed it from a notice to a warning, and many hosts show warnings but hid notices. The bug was always there.

What value does an undefined variable have?

PHP treats it as null and continues. That can lead to wrong totals, empty output or later TypeErrors.

Can I use the global keyword instead?

global $total; works but makes code harder to follow and test. Passing the value as a parameter is the better fix.