What is Notice: Undefined variable in PHP and Solution?

The biggest challenge in front of web developer is to run PHP scripts without any errors and warnings.

PHP: Notice undefined variable is the one of the warning, we encounter.

Why warning or notice, ‘Undefined variable’ rises?

As the warning or notice says, undefined variable, the variable is not defined and we are trying to access the variable later in the script. This happens, because somewhere in the PHP script we have assigned value to the variable directly. It also rises if we have appended a PHP script with another PHP Script. Apache Server unable to understand the variable. Therefore, such variable appear empty or not defined to the server.

Solutions:

1.Such warnings are not effecting the performance of the PHP Script. So we can hide the warning.

error_reporting( error_reporting() & ~E_NOTICE )

The above code would hide the notice.

2. If you have turned on to appear the notices in the php script, then you can redirect it to a error log file.

set_error_handler(‘errorsnoticelist’, E_NOTICE | E_STRICT)

It will set all the PHP notice to the error log file ‘errorsnoticelist’

3. The best solution: Declare empty variable first and then assign value.

$val=””;

$val=5000;

The above code is efficient one. It wont raise, PHP Notice: Undefined variable.

It is good practice to declare all the variables with empty value first and then assign values as required.