PHP读取‘get’可能已设置或未设置的变量
如果您尝试读取“get”变量的值,如果该变量尚未在 URL 中设置,会发生什么情况。示例:您请求页面 test.php
,在该文件中它尝试读取 $_GET['message']
的值。在这种情况下会发生什么?该值是否会以 ''
形式返回?
这是否意味着,如果我总是期望输入一个值,并且不愿意接受 '' 值,我可以做类似的事情,
$foo = $_GET['bar'];
if($foo == ''){
// Handle my 'error'
}
else
{
// $foo should now have a value that I can work with
}
请记住我知道我可以使用 isset($_GET ['bar'])
但我不仅仅想知道它是否已设置,我不在乎它是否设置,我只关心它的值是否不仅仅是一个空值细绳。
If you try to read the value of a 'get' variable, what happens if said variable had not been set in the URL. Example: you request the page test.php
, in that file it tries to read the value of $_GET['message']
. What happens in this case? dose the value just get returned as ''
?
Does this mean that if I am always expecting a value to be entered, and am not willing to accept a value of '' that I can just do something like
$foo = $_GET['bar'];
if($foo == ''){
// Handle my 'error'
}
else
{
// $foo should now have a value that I can work with
}
Please keep in mind I know that I could use isset($_GET['bar'])
But I don't just want to know if it is set, I don't care if it is or not, I just care if it has a value that is more than just an empty string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您不关心该值是否实际设置,您可以使用:
If you don't care if the value is actually set, you can use this:
如果您尝试访问不存在的数组项,结果将为
null
。值得注意的是,如果您使用的是弱比较运算符
==
而不是严格比较===
,那么''
将被视为 null。上面代码的缺点是,当您使用不存在的索引访问数组时,它会生成一个通知,这有点混乱。
因此,在将包含的值分配给变量之前,应该检查该值是否已设置。
如果您想要一个默认值,并且仅在 $_GET 值存在时替换该默认值,您可以使用 条件运算符(向下滚动到“三元运算符”)
If you try and access an array item that doesn't exist, the result will be
null
.It is worth noting that if you are using the weak comparison operator
==
rather than the strict comparsion===
, then''
will be treated as null.The downside with the above code is that it will generate an notice when you access the array with an index that doesn't exist which is a bit messy.
Hence you should check if the value is set before you assign the contained value to a variable.
If you want to have a default value, and only replace that default value if the $_GET value exists you can use the conditional operator (scroll down to "Ternary Operator")
我是这样做的。
另一方面,您可能永远不会从 $_GET 获得真正的布尔值
Here is how I do it.
As a side, you will probably never get a true Boolean value from $_GET
如果我理解正确的话是:
If I understand correctly it's:
另一种方法是使用 PHP 的 filter_input 函数:
Another way is to use PHP's filter_input function: