Tutorial :PHP Undefined Index



Question:

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);      }  


Solution:1

you should use the following approach:

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


Solution:2

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

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


Solution:3

"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'];  }  


Solution:4

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.


Solution:5

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
Previous
Next Post »