PHP Basics

What does notice: Undefined Variable in PHP Scripting mean?

The notice: undefined variable means, as the name it says, the variable is not defined.

Notice undefined variable

Look at the below code

<?php

if(!empty($employees_data)){

$employee_phone_number=Get_Employee_Phone_Number();

}

echo $employee_phone_number

?>

Can you guess, what would be the result?

It will show, Notice: undefined variable error.

Reason: the variable $employee_phone_number variable is defined inisde the if block so it is not available outside the if block.

To avoid the notice “undefined variable” then either we have to check whether the variable is not empty or isset, or define empty variable before the if blcok.

Solution 1

<?php

if(!empty($employees_data)){

$employee_phone_number=Get_Employee_Phone_Number();

}

if(!empty($employee_phone_number)){

echo $employee_phone_number;

}

?>

solution 2

<?php

if(!empty($employees_data)){

$employee_phone_number=Get_Employee_Phone_Number();

}

if(isset($employee_phone_number)){

echo $employee_phone_number;

}

?>

Solution 3

<?php

$employee_phone_number=”;

if(!empty($employees_data)){

$employee_phone_number=Get_Employee_Phone_Number();

}

 

echo $employee_phone_number;

 

?>

 

Another Case

In so many cases we often include separate php script files to get result. In such scenario, we have call a variable straight then it will show the warning message.

Example

file1.php -> $age, $employee_id

file2.php-> $employee_address, $employee_tasks

file3.php->$employee_tax_details

file4.php -> $file1.php+$file2.php+$file3.php+$file4.php

$file4.php-> $employee_family_data

Output: Notice: Undefined variable employee_family_data

Reason: file4.php has included file1.php, file2.php,file3.php. $file4.php is trying to access the variable $employee_family_data which is not defined earlier. Hence it will throw the notice.

Solution

Before using any variable in the php script we must have to check whether the variable is valid.

We do this, using empty function or isset function.

Example

if(!empty($employee_family_data)){

// $employee_family_data is available. use it in the code.

}

Example

if(isset($employee_family_data)){

// $employee_family_data is available. use it in the code.

}