- PHP

Notice: Undefined variable in PHP

This error is displayed if you refer to a variable that doesn’t exist in your code.

Notice: Undefined variable: testVariable in C:\xampp\htdocs\snippetsdb\index.php on line 3

This error should show you the:

  • Variable name (in this example, testVariable)
  • Problematic file (in this example, C:\xampp\htdocs\snippetsdb\index.php)
  • Code line in which variable is used (in this example, on line 3)

Make sure that you didn’t misspell the variable name, and check if it’s included in your file. To avoid these types of notice, use the isset() function.

How to fix Undefined variable notice in PHP

Sometimes we may even want to refer to variables that wouldn’t exist under some conditions.

To avoid “Undefined variable” notice, use the isset() function and always check if it’s declared.

<?php

if(isset($variable)) {
    // do something
}

?>

Example:

This will display the “Undefined variable” notice.

<?php

echo $ourUndefinedVariable;

?>

While this should work perfectly fine, and don’t display anything if the variable wasn’t declared before.

<?php

if(isset($variable)) {
    echo $variable;
}

?>