PHP Notice: Undefined variable fix

January 16, 2013 in php scripts

This warning is generated when a variable is not defined in php.
Using the following example i`l generate this notice and i will explain how to avoid this.
Assuming this to be a file named : testfile.php

<?php
$variable1 =$_GET['variable'];
echo $variable1;
?>

Accessing testfile.php from browser will give the following notice :

PHP Notice:  Undefined index: variable in testfile.php on line 2

Now let’s fix it :

<?php
if (isset($_GET['variable'])){
   $variable1=$_GET['variable'];
   echo $variable1;
}
?>

Isset checks if a variable is defined or not. If is defined will execute it , if not will ignore it but will not generate any notice.

  • RYan

    Simple answer thank you