[英]The php if(isset($_GET['something'])) is not working
[英]isset PHP isset($_GET['something']) ? $_GET['something'] : ''
我希望扩展我的 PHP 知识,但我遇到了一些我不确定它是什么或如何搜索它的东西。 我正在查看 php.net isset 代码,我看到了isset($_GET['something']) ? $_GET['something'] : ''
isset($_GET['something']) ? $_GET['something'] : ''
我理解正常的 isset 操作,例如if(isset($_GET['something']){ If something is exists, then it is set and we will do something }
但我不明白 ?,再次重复 get, : 或 ''。有人可以帮我分解一下,或者至少为我指明正确的方向吗?
它通常被称为“速记”或三元运算符。
$test = isset($_GET['something']) ? $_GET['something'] : '';
方法
if(isset($_GET['something'])) {
$test = $_GET['something'];
} else {
$test = '';
}
分解:
$test = ... // assign variable
isset(...) // test
? ... // if test is true, do ... (equivalent to if)
: ... // otherwise... (equivalent to else)
要么...
// test --v
if(isset(...)) { // if test is true, do ... (equivalent to ?)
$test = // assign variable
} else { // otherwise... (equivalent to :)
这称为三元运算符,主要用于代替 if-else 语句。
在您给出的示例中,它可用于从给定 isset 返回 true 的数组中检索值
isset($_GET['something']) ? $_GET['something'] : ''
相当于
if (isset($_GET['something'])) {
$_GET['something'];
} else {
'';
}
当然,除非您将其分配给某些东西,否则它没有多大用处,甚至可能为用户提交的值分配一个默认值。
$username = isset($_GET['username']) ? $_GET['username'] : 'anonymous'
您遇到了 三元运算符。 它的目的是一个基本的 if-else 语句。 下面几段代码做同样的事情。
三元:
$something = isset($_GET['something']) ? $_GET['something'] : "failed";
如果别的:
if (isset($_GET['something'])) {
$something = $_GET['something'];
} else {
$something = "failed";
}
它被称为三元运算符。 它是 if-else 块的简写。 参见这里的示例http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
? 称为三元(条件)运算符: 示例
如果您想要一个空字符串默认值,那么首选方法是其中之一(取决于您的需要):
$str_value = strval($_GET['something']);
$trimmed_value = trim($_GET['something']);
$int_value = intval($_GET['somenumber']);
如果 url 参数中的something
在 url中不存在,则$_GET['something']
将返回null
strval($_GET['something'])
-> strval(null)
-> ""
并且您的变量$value
设置为空字符串。
trim()
可能比strval()
(例如 Name 参数可能想要使用它)intval()
如果只需要数字值并且默认值为零。 intval(null)
-> 0
需要考虑的情况:
...&something=value1&key2=value2
(典型)
...&key2=value2
(url $_GET 中缺少的参数将为其返回 null)
...&something=+++&key2=value
(参数为" "
)
为什么这是首选方法:
$value = isset($_GET['something']) ? $_GET['something'] : '';
可读$value = isset($_GET['something']) ? $_GET['something'] : '';
$value = isset($_GET['something']) ? $_GET['something'] : '';
$value=isset($_GET['something'])?$_GET['somthing']:'';
更新严格模式可能需要这样的东西:
$str_value = strval(@$_GET['something']);
$trimmed_value = trim(@$_GET['something']);
$int_value = intval(@$_GET['somenumber']);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.