Undefined Variable

Warning: Undefined variable $username

Quick Answer

You are using a variable that has not been assigned a value in the current scope. Initialize the variable before using it or check if it exists with isset().

Why This Happens

PHP raises this warning when you reference a variable that was never defined or is out of scope. This commonly happens when you misspell a variable name, forget to initialize it before a conditional block, or expect a variable from a different scope like inside a function.

The Problem

function greet() {
    echo "Hello, $username";
}
$username = "Alice";
greet();

The Fix

function greet(string $username) {
    echo "Hello, $username";
}
$username = "Alice";
greet($username);

Step-by-Step Fix

  1. 1

    Identify the variable

    Look at the warning message to find which variable is undefined and on which line it is used.

  2. 2

    Trace the assignment

    Check if the variable was assigned before the line that uses it. Look for typos, scope issues, or conditional branches that skip assignment.

  3. 3

    Initialize or pass the variable

    Either initialize the variable with a default value, pass it as a function parameter, or use the global keyword if needed.

Got the actual stack trace?

Paste it into our free AI explainer to get the cause and the fix for your specific case — no signup, nothing to install.

Explain my error

Bugsly catches this automatically

Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.

Try Bugsly free