题
下面的内容似乎没有按照我的预期工作,尽管 $_GET['friendid'] = 55 它返回 NULL
<?PHP
$_GET['friendid'] = 55;
$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';
echo $friendid;
exit;
?>
解决方案
取出!
。你不想否定的表达。
$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
其他提示
作为 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';
打破它的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
条件为假,并将其传递到else
选项。
在这种情况下,设置$friendid
变量的值,以empty
。
你想要的是删除感叹号,然后,如果它先前已经设定$friendid
的价值将在$_GET['friendid']
的值。
如果friendid是不会设置,friendid = friendid否则friendid =空
好吧,我可能已经有一个类似的问题不熟悉的!情况作为jasondavis了。
的混淆类,而是发现不具有!在... isset($阿瓦尔)相比!isset($阿瓦尔)可以使相当的差异。
于是用!到位,更说明一个YES如
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';
远远更少混淆与如果A $ =“”,那么....解决它。 (或者如果$ A = “” 为那些PHP的)。
我觉得这是使用字符串和变量的所有字符串形式有时是会非常艰巨。甚至通过混淆,其实我可以理解为什么......只是刁难一点点把握我。