并且不能让这个工作。我想从URL获取变量,例如:
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";
}
}
这确实有效。但是如果参数输入错误,例如:
domain.com?asdasd=whatever
我收到错误:
“注意:未定义的索引:第19行的test.php中的区域”
您能否告诉我如何防止此错误出现并将其视为空变量并返回“American”?
我尝试了这段代码,但它不起作用:
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";
}
}
即使URL为true:
domain.com?region=Texas
仍然在输出中获得“Anything Else”。
答案 0 :(得分:1)
USE $ _GET ['region']而不是$ _GET本身
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";
}
}
答案 1 :(得分:1)
使用isset(($_GET['region'])
,因为如果输入未定义的变量,它不会发出通知:
if (!isset($_GET['region'])) {
echo 'American';
} else {
$t = $_GET["region"];
if ($t == "Texas") {
echo "Texan";
} elseif ($t == "California") {
echo "Californian";
} else {
echo "American";
}
}
答案 2 :(得分:1)
您可以使用array_key_exists('region',$_GET)
来测试参数是否存在,或许
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';
}
答案 3 :(得分:1)
试试这个:
<?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";
}
}
?>