PHP GET 问题:仅当变量值不在查询字符串中时,如何设置变量值?
如果参数存在,我知道如何从查询字符串中获取值:
$hop = $_GET['hop'];
但如果它不在查询字符串中,我还需要设置一个默认值。我尝试了这个,但没有成功:
$hop = $_GET['hop'];
if ($hop = " ") {
$hop = 'hardvalue';
};
请帮助我处理查询字符串有和没有“hop”参数的情况,以及如果它存在但未定义:
example.com/?hop=xyz
&
example.com/
&
example.com/?hop=
PS 我不知道我在做什么,所以如果你向我解释,请还包括我要添加到我的 PHP 页面的确切代码。
I know how to get the value from the query string if the parameter exists:
$hop = $_GET['hop'];
But I also need to set a default value IF it's not in the query string. I tried this and it didn't work:
$hop = $_GET['hop'];
if ($hop = " ") {
$hop = 'hardvalue';
};
Please help me handle the case where the query string has and does not have the "hop" parameter, and if it's present but not defined:
example.com/?hop=xyz
&
example.com/
&
example.com/?hop=
PS I don't know what I'm doing, so if you explain to me, please also include the exact code for me to add to my PHP page.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
array_key_exists
use
array_key_exists
再想一想,决定它应该更健壮一点:
Thought about it a bit more and decided it should be a bit more robust:
你已经得到了复杂的解决方案。使用 URL 或表单参数时,您通常也希望将空字符串或零视为缺失值。然后您可以使用这种替代语法:
它之所以有效,是因为
=
比or
具有更高的优先级,并且使用额外的空格更容易阅读。从 PHP 5.3 开始,还可以使用:
这里的优点是这种语法不会占用 php 通知,这对于调试很有用。
You already got the fiddly solutions. When working with URL or form parameters, you often want to treat the empty string or zeros as absent values too. Then you can use this alternative syntax:
It works because of the higher precedence of
=
overor
, and is easier to read with extra spaces.Starting from PHP 5.3 it's also possible to use:
The advantage here is that this syntax doesn't slurp up php notices, which are useful for debugging.
实际上,我会使用
使用
empty()
而不是isset()
来处理第三种情况,其中参数存在但未定义。另外,在
if ($hop = " ")
中,=
需要更改为==
。=
分配,==
测试相等。按照您的方式,if 语句将始终运行,无论$hop
等于什么。Actually, I would use
Using
empty()
instead ofisset()
takes care of your third scenario, where the parameter is present but not defined.Also, in
if ($hop = " ")
the=
would need to be changed to==
.=
assigns,==
tests equality. The way you have it, the if-statement will always run, no matter what$hop
equaled.