Tutorial :PHP Undefined Index


I have this code and it's giving me an undefined error if country is not a variable in the URL. I've never had this problem before so it's obviously something to do with server settings but I'd rather not change those because this is probably done for security purposes. I've searched Google and can't find the workaround, although I'm sure it's blindingly obvious!

$country = $_GET['country'];        if(!$country){          $incoming = $outgoing = $sms = $free = "---";      } else {          get_rates($country);      }  


you should use the following approach:

if (!isset($_GET['country'])) {      $incoming = $outgoing = $sms = $free = "---";  } else {      get_rates($_GET['country']);  }  


isset allows you to check if the variable exists (if not we give it the value false).

$country = isset($_GET['country'])?  $_GET['country'] : false;  


"Undefined index" means that element doesn't exist in the array. Your server is probably set to report these errors, while your system so far wasn't. Check if the element exists before accessing it.

$country = null;  if (!empty($_GET['country']) {      $country = $_GET['country'];  }  


You should probably check to see if $_GET['country'] is set. I would wrap the entire code block you posted in an if statement that checks if the country field is set, using the isset function.


Just change:

$country = $_GET['country'];  

To this:

$country = @$_GET['country'];  

'@' is an operator which will remove errors output.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »