Register Login

Notice: Undefined Variable in PHP

Updated Mar 05, 2020

Notice: Undefined variable

This error means that within your code, there is a variable or constant which is not set. But you may be trying to use that variable.

The error can be avoided by using the isset() function.This function will check whether the variable is set or not.

Error Example:

<?php
$name='Stechies';
echo $name;
echo $age;
?>

Output:

STechies
Notice: Undefined variable: age in \testsite.loc\varaible.php on line 4

In the above example, we are displaying value stored in the ‘name’ and ‘age’ variable, but we didn’t set the ‘age’ variable.

Notice: Undefined offset error in PHP

Here are two ways to deal with such notices.

  1. Resolve such notices.
  2. Ignore such notices.

Fix Notice: Undefined Variable by using isset() Function

This notice occurs when you use any variable in your PHP code, which is not set.

Solutions:

To fix this type of error, you can define the variable as global and use the isset() function to check if the variable is set or not.

Example:

<?php
global $name;
global $age;
$name = 'Stechies';

if(!isset($name)){
$name = 'Variable name is not set';
}
if(!isset($age)){
$age = 'Varaible age is not set';
}
echo 'Name: ' . $name.'<br>';
echo 'Age: ' . $age;
?>

Set Index as blank

<?php
$name = 'Stechies';

// Set Variable as Blank
$name = isset($name) ? $name : '';
$age= isset($age) ? $age: '';

echo 'Name: ' . $name.'<br>';
echo 'Age: ' . $age;
?>

Ignore PHP Notice: Undefined variable

You can ignore this notice by disabling reporting of notice with option error_reporting.

1. Disable Display Notice in php.ini file

Open php.ini file in your favorite editor and search for text “error_reporting” the default value is E_ALL. You can change it to E_ALL & ~E_NOTICE.

By default:

error_reporting = E_ALL

Change it to:

error_reporting = E_ALL & ~E_NOTICE

Now your PHP compiler will show all errors except 'Notice.'

2. Disable Display Notice in PHP Code

If you don’t have access to make changes in the php.ini file, In this case, you need to disable the notice by adding the following code on the top of your PHP page.

<?php error_reporting (E_ALL ^ E_NOTICE); ?>

Now your PHP compiler will show all errors except 'Notice.'


×