Reputation: 253
and can't get this to work. I want to get variable from URL, like:
domain.com?region=STATE
if (empty($_GET)) {
echo 'American';
}
else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
This does work. However in case there's wrong parameter input, like:
domain.com?asdasd=whatever
I get an error:
"Notice: Undefined index: region in test.php on line 19"
Can you tell me how can I prevent this error from appearing and basically treat it as empty variable and return "American" instead?
I tried this code, but it doesn't work:
if (empty($_GET)) {
echo 'American';
}
elseif ($_GET != "region") {
echo 'Anything Else';
}
else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
Even if URL is true:
domain.com?region=Texas
is still get "Anything Else" in the output.
Upvotes: 0
Views: 355
Reputation: 308
Try this too:
<?php
if (empty($_GET)) {
echo 'American';
} else if($_GET){
echo 'No Error! (Anything Else)';
}
else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
?>
Upvotes: 1
Reputation: 33813
You could use array_key_exists('region',$_GET)
to test if the parameter exists like this perhaps
if( !empty( $_GET ) ){
$t = array_key_exists( 'region', $_GET ) && !empty( $_GET['region'] ) ? strtolower( $_GET['region'] ) : false;
if( $t ){
switch( $t ){
case 'texas': echo 'Texan';break;
case 'california': echo "Californian"; break;
default: echo 'Other State'; break;
}
} else {
echo 'Anything Else';
}
} else {
echo 'American';
}
Upvotes: 1
Reputation: 766
USE $_GET['region'] not $_GET itself
if (!isset($_GET["region"]) || empty($_GET["region"])) {
echo 'American';
}
else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
Upvotes: 1
Reputation: 2126
Use isset(($_GET['region'])
as it does not emit a notice if fed an undefined variable:
if (!isset($_GET['region'])) {
echo 'American';
} else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
Upvotes: 1