PromptHub
PHP Beginner 16 views

Undefined Variable

The code references a variable that has not been declared or assigned a value.

Explanation

Undefined variable warning occurs when PHP encounters a variable name that hasn't been initialized before it's used. In PHP 8+, this is an Error exception; in earlier versions, it was a notice. Variables in PHP must be assigned before use, though they can be created implicitly in some contexts. This error commonly happens due to typos in variable names, scoping issues where a variable defined inside a function isn't available outside, or using variables from foreach loops outside the loop scope.

Common Causes

  • Variable name typo
  • Variable used before assignment
  • Variable scope mismatch
  • Conditional assignment skipped
  • Missing variable initialization

Solution

Initialize all variables before using them, even if assigning a default value like null or empty array. Use strict mode (declare(strict_types=1)) to catch type-related issues. Check variable names for typos. Ensure variables defined in foreach loops are initialized before the loop if needed afterward. Use isset() or null coalescing operator (??) to check if a variable exists before accessing it. Enable error reporting in development to catch these issues early.

Code Example

// Undefined variable due to typo
$name = 'John';
echo $nmae; // typo! Undefined variable $nmae

// Fix
echo $name;

// Scoping issue with foreach
foreach ($users as $user) {
    $name = $user->name;
}
echo $name; // May be undefined if $users is empty

// Fix: initialize before loop
$name = null;
foreach ($users as $user) {
    $name = $user->name;
}

// Use null coalescing for safe access
echo $variable ?? 'default';

// Check existence before use
if (isset($variable)) {
    echo $variable;
}

Error Information

Language

php

Difficulty

Beginner

Views

16

Related Errors