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
348
Related Errors
PHP
Parse Error: Syntax Error
PHP detected a syntax error in the source code that prevents parsing.
Laravel
MalformedPayloadException
The request payload or session data is corrupted or invalid.
Database
Too Many Connections
The database server has reached its maximum connection limit.
Database
Column Count Doesn't Match
The number of values in an INSERT statement doesn't match the number of columns.