所以,我有一些PHP代码,看起来有点像这样:
The ID is
现在,当我传递一个ID,比如
它工作得很好,但是如果没有像这样的ID
然后输出:
The ID is
Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9
!
我一直在寻找解决这个问题的方法,但我找不到任何方法来检查URL变量是否存在。但我知道一定有办法。
发布于 2012-08-18 23:15:12
您可以使用
功能:
if(isset($_GET['id'])) {
// id index exists
}
如果index不存在,您可以创建一个方便的函数来返回默认值:
function Get($index, $defaultValue) {
return isset($_GET[$index]) ? $_GET[$index] : $defaultValue;
}
// prints "invalid id" if $_GET['id'] is not set
echo Get('id', 'invalid id');
您也可以尝试同时验证它:
function GetInt($index, $defaultValue) {
return isset($_GET[$index]) && ctype_digit($_GET[$index])
? (int)$_GET[$index]
: $defaultValue;
}
// prints 0 if $_GET['id'] is not set or is not numeric
echo GetInt('id', 0);
发布于 2012-08-18 23:15:45
if (isset($_GET["id"])){
//do stuff
}
发布于 2012-08-18 23:19:26
通常情况下,这样做是很好的:
echo isset($_GET['id']) ? $_GET['id'] : 'wtf';
在将var赋值给其他变量时,您可以一口气完成所有默认值,而不是不断使用
语句,以便在未设置这些语句的情况下仅为其提供默认值。
https://stackoverflow.com/questions/12019684
复制相似问题