4

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);
 }
asked Jul 16, 2009 at 11:37
0

5 Answers 5

14

you should use the following approach:

if (!isset($_GET['country'])) {
 $incoming = $outgoing = $sms = $free = "---";
} else {
 get_rates($_GET['country']);
}
answered Jul 16, 2009 at 11:40
3
  • 1
    Actually, I think you want if(!isset(...)) { Commented Jul 16, 2009 at 11:43
  • You are missing a closing ']' bracket in the if statement Commented Jul 16, 2009 at 12:37
  • $country = @$_GET['country']; // the OLD PHP way to avoid notices Commented Sep 25, 2011 at 14:42
4

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

$country = isset($_GET['country'])? $_GET['country'] : false;
answered Jul 16, 2009 at 11:39
2

"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'];
}
answered Jul 16, 2009 at 11:40
1

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.

answered Jul 16, 2009 at 11:41
-1

Just change:

$country = $_GET['country'];

To this:

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

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

answered Jul 16, 2009 at 11:39
4
  • 10
    that's the worst piece of advice one could give Commented Jul 16, 2009 at 11:40
  • In this case it's ok because there's a check just after. Commented Jul 16, 2009 at 11:41
  • using @ error supressor is quite a stinky code smell, read about code smells on SO Commented Jul 16, 2009 at 11:42
  • 3
    @ IS OK for some contexts, in conscious use. It is NOT A DEPRECATED operator. The main typical use is with $_POST and $_GET, like '<input name="x" value="<?= $_POST['x']?>"/>'. The FWH suggestion is good: initialize $contry with '' or with a value, there are NO SIDE EFFECT! Commented Sep 25, 2011 at 15:04

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.