Notice: Undefined variable in PHP

What does this error mean? Notice: Undefined variable in PHP

This error message is meant to help PHP developers spot a typo or a mistake when accessing a variable (or an array element) that doesn't exist. So a good programmer:

  1. Makes sure every variable or array key is already defined at the point where it is used. If a variable needs to be used inside a function, it must be passed to that function as a parameter.

  2. Pays attention to this error and fixes it, just like any other error. It may point to a spelling mistake, or to some procedures not returning the expected data.

  3. Only in rare cases, when things are outside the developer's control, can code be added to work around this error. But it should never become a habit.


PHP doesn't require variables to be declared, but doing so is recommended to avoid certain security vulnerabilities or bugs where you might forget to give a value to a variable that will be used later in the script. For undeclared variables, PHP raises an E_WARNING level error.

This warning helps developers spot a misspelled variable name or a similar kind of mistake (such as a variable that was assigned a value inside a condition that evaluated to false). There may also be other issues with uninitialized variables.

It's best to initialize all variables in a PHP file before using them.

Recommended solution: declare every variable before using it.

That way, you will only see this error when you actually make a mistake by trying to use a variable that doesn't exist, which is precisely what this error message is for.

// Initializing a variable
$valeur = ""; // Initial value: 0 for an integer, [] for an array, etc.
echo $valeur; // no error
echo $valuer; // an error points to a misspelled variable name

A special case arises when a variable is defined but isn't visible inside a function. Functions in PHP have their own variable scope, and if you need to use a variable from outside inside a function, its value must be passed as a parameter of the function:

function test($param) {
return $param + 1;
}
$var = 0;
echo test($var); // the value of $var is now available inside via $param

Another solution: suppress the error with the null coalescing operator.

But keep in mind that this way, PHP won't be able to warn you when you use the wrong variable name.

// The null coalescing operator
echo $valeur ?? '';

For older versions of PHP (< 7.0), isset() with a ternary can be used.

 echo isset($value) ? $value : '';

Be aware, though, that this is essentially error suppression, just for one particular error. It can therefore stop PHP from helping you by flagging an uninitialized variable.

Suppress the error with the @ operator.

Left here for historical reasons, but it simply shouldn't be used.

Have a web project in mind?

Website design, e-commerce or SEO: our web agency in Paris, Besançon and Normandy can help.

Free quote

Related articles