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);
}
5 Answers 5
you should use the following approach:
if (!isset($_GET['country'])) {
$incoming = $outgoing = $sms = $free = "---";
} else {
get_rates($_GET['country']);
}
-
1Actually, I think you want if(!isset(...)) {Thomas Owens– Thomas Owens2009年07月16日 11:43:20 +00:00Commented Jul 16, 2009 at 11:43
-
You are missing a closing ']' bracket in the if statementShoan– Shoan2009年07月16日 12:37:53 +00:00Commented Jul 16, 2009 at 12:37
-
$country = @$_GET['country']; // the OLD PHP way to avoid noticesPeter Krauss– Peter Krauss2011年09月25日 14:42:22 +00:00Commented Sep 25, 2011 at 14:42
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.
-
10that's the worst piece of advice one could giveSilentGhost– SilentGhost2009年07月16日 11:40:33 +00:00Commented Jul 16, 2009 at 11:40
-
In this case it's ok because there's a check just after.FWH– FWH2009年07月16日 11:41:41 +00:00Commented Jul 16, 2009 at 11:41
-
using @ error supressor is quite a stinky code smell, read about code smells on SOmarkus– markus2009年07月16日 11:42:24 +00:00Commented 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!Peter Krauss– Peter Krauss2011年09月25日 15:04:40 +00:00Commented Sep 25, 2011 at 15:04