下面的这似乎不像我期望的那样工作,尽管 $_GET['friendid'] = 55 它返回 NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
下面的这似乎不像我期望的那样工作,尽管 $_GET['friendid'] = 55 它返回 NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
自PHP 7 发布以来,您可以为此使用空合并运算符(双“?”):
$var = $array["key"] ?? "default-value";
// which is synonymous to:
$var = isset($array["key"]) ? $array["key"] : "default-value";
在 PHP 5.3+ 中,如果您检查的只是一个“真实”值,您可以使用“Elvis 运算符”(注意这不会检查 isset)。
$var = $value ?: "default-value";
// which is synonymous to:
$var = $value ? $value : "default-value";
删除!
. 您不想否定表达式。
$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
如果您懒惰且冒险,则可以使用错误控制运算符 @和三元运算符的缩写形式。
$friendid = @$_GET['friendid']?: 'empty';
目前您正在使用三元运算符:
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
将其分解为一个if-else
语句,它看起来像这样:
if(!isset($_GET['friendid']))
$friendid = $_GET['friendid'];
else
$friendid = 'empty';
看看if
声明中真正发生了什么:
!isset($_GET['friendid'])
isset
请注意函数前面的感叹号 (!) 。这是另一种说法,“相反”。您在这里所做的是检查$_GET['friendid']
. 如果是这样,$friendid
应该采用该值。
但实际上,它会破裂,因为$_GET['friendid']
它甚至不存在。你不能接受不存在的东西的价值。
从一开始,您就为 设置了一个值$_GET['friendid']
,因此第一个if
条件现在为 false 并将其传递给else
选项。
在这种情况下,将$friendid
变量的值设置为empty
。
您想要的是删除感叹号,然后 的值$friendid
将采用$_GET['friendid']
先前设置的值。
从您对 Philippe 的回复中,我认为您需要看看empty和isset之间的区别。
总而言之,isset()
如果变量存在,将返回布尔值 TRUE。因此,如果你要
$fid = $_GET['friendid'] = "";
$exists = isset($fid);
$exists
将是 TRUE$_GET['friendid']
存在。如果这不是你想要的,我建议你看看空。Empty 将在空字符串 ("") 上返回 TRUE,这似乎是您所期望的。如果您确实使用空,请参阅我链接到的文档,还有其他情况下空会在您可能不期望的情况下返回 true,这些情况在上面的链接中明确记录。
我在这样的条件下使用Null 合并运算符运算符
if($myArr['user'] ?? false){
这相当于
if(isset($myArr['user']) && $myArr['user']){
如果没有设置friendid,则friendid =friendid否则friendid =空
好的,我可能遇到了类似的问题,不熟悉!像jasondavis那样的情况。
有点令人困惑,但发现没有!如... isset($avar) 与 !isset($avar) 相比可以产生很大的不同。
所以用!到位,更像是在
since $_GET['friendid'] = 55; has been initialized...
tell me 'no' - the opposite - that it hasn't and set it to empty.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
where not having the ! tells me yes it has something in it, leave it be.
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
与 if A$="" then.... 的混淆要少得多。(或者如果 $A="" 对于那些 PHP )。
我发现将字符串和变量都作为字符串使用有时非常令人生畏。即使在困惑中,我实际上也能理解为什么……只是让事情对我来说有点难以理解。