undefined variable in php

How to Fix Notice: Undefined Variable in PHP

PHP is a powerful programming language used by many websites around the world. However, sometimes PHP may throw an error message saying “Notice: Undefined Variable” on your website. This can confuse your website visitors and spoil their user experience. In this article, we will look at what this error message means and how to fix this error message.


How to Fix Notice: Undefined Variable in PHP

When you get an error message “Notice: Undefined Variable” in PHP it means that you are trying to use a variable or constant that is not defined.

Here is an example of this error

<?php 
$dob='2021-01-01'; 
echo $age; 
?>

In the above example, we have defined $dob variable but are calling $age variable which is not defined. So you will see the following error.

Notice: Undefined variable: age in \test.php on line 3

There are two ways to fix this error. Either you can resolve this error or ignore this error.

Also read : How to Run PHP Scripts Automatically


Fix Error using isset() function

You can use define your variables as global and use isset() function to test if the variable is set or not before calling it. Here is an example

<?php
global $age;
global $dob = '2021-01-01';


if(!isset($age)){
$age = 'Variable age is not set';
}

echo 'Age: ' . $age;
?>
Output
Variable age is not set

Also read : How to Disable Directory Browsing in Apache


Fix Error by setting variable as blank or default value

Another way to fix this problem, is to set it as blank.

<?php
$dob = '2021-01-01';

// Set Variable as Default
$age= isset($age) ? $age: '0';

echo 'Age: ' . $age;
?>

Output
Age: 0

Also read : How to Prevent Direct File Download in Apache

We can also ignore this notice instead of fixing it, though it is not advisable to do so. Here are a couple of ways to disable this error message from appearing.


Disable Display Notice in php.ini file

Open php.ini file in a text editor. Look for the following line

error_reporting = E_ALL

Change it to

error_reporting = E_ALL & ~E_NOTICE

Restart Apache server to apply changes. Now PHP compiler will show all errors except ‘NOTICE’ type of errors.

Also read : How to Check if mod_deflate is Enabled


Disable displaying Notice in PHP code

If you don’t have access to php.ini file, then just add the following line at the top of your php file to disable notice errors.

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

That’s it. In this article, we have learnt how to deal with “Undefined Variable” error in PHP. Using variables without defining their values causes this error, and can be easily avoided by using isset() function to check if they are set or not, before using them.

Also read : How to Limit Requests Per IP in Apache


Leave a Reply

Your email address will not be published. Required fields are marked *