在 PHP 中检查 null 和缺失的查询字符串参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4382669/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking for null and missing query string parameters in PHP
提问by Yarin
I want to be able to distinguish between existing query string parameters set to null, and missing parameters. So the parts of the question are:
我希望能够区分设置为 null 的现有查询字符串参数和缺少的参数。所以问题的部分是:
- How do I check if a parameter existsin the query string
- What's the established method for passing a null value in a query string? (e.g. param=null or param=(nothing) )
- 如何检查查询字符串中是否存在参数
- 在查询字符串中传递空值的既定方法是什么?(例如 param=null 或 param=(nothing) )
Thanks
谢谢
回答by Byron Whitlock
回答by karim79
Or use array_key_exists:
或使用array_key_exists:
if(array_key_exists("myParam", $_GET)) {
}
I've never been keen on 'conventions' for passing empty values to the server - I'm used to testing for the presence of variables, and then trimming them and testing for emptiness, for example.
我从不热衷于将空值传递给服务器的“约定”——例如,我习惯于测试变量是否存在,然后修剪它们并测试是否为空。
回答by zzzzBov
Values stored in $_GETand $_POSTcan only be strings or arrays, unless explicitly set at run-time. If you have a query string of query=stringthe value is "string"if you instead use: query=nullthe value will be "null". Note that it is therefor a string.
存储在$_GET并且$_POST只能是字符串或数组的值,除非在运行时明确设置。如果您有一个query=string值的查询字符串,"string"如果您改为使用:query=null该值将为"null". 请注意,它是一个字符串。
If you send: query=, the value will be ""or the empty string. Take note of the differencesbetween issetand empty. issetwill be true if the value is not null, whereas emptywill be true when the value evaluates to false. Therefor ""will be true for bothissetand empty.
如果您发送: query=,则该值将是""或 空字符串。记的差异之间isset和empty。isset如果值不为空,则为empty真,而当值计算为 时为真false。为此"",将成为真正既isset和empty。
If you just want to check if a query string parameter was set to the string value of "null", you can simply check $_GET['query']=='null'(you may want to adjust the case of the characters before the check)
如果只想检查一个查询字符串参数是否设置为 的字符串值"null",您可以简单地检查$_GET['query']=='null'(您可能需要在检查前调整字符的大小写)
回答by MatthewK
With one if statement instead of two:
用一个 if 语句而不是两个:
if ((isset($_REQUEST['name'])) && (!empty($_REQUEST['name'])))
{
$name= $_REQUEST['name'];
}

