29

下面的这似乎不像我期望的那样工作,尽管 $_GET['friendid'] = 55 它返回 NULL

<?PHP

$_GET['friendid'] = 55;

$friendid = (!isset($_GET['friendid'])) ? $_GET['friendid'] : 'empty';

echo $friendid;
exit;

?>
4

9 回答 9

67

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";
于 2015-03-05T16:45:01.390 回答
52

删除!. 您不想否定表达式。

$friendid = isset($_GET['friendid']) ? $_GET['friendid'] : 'empty';
于 2009-08-08T13:24:23.710 回答
11

如果您懒惰且冒险,则可以使用错误控制运算符 @和三元运算符的缩写形式。

$friendid = @$_GET['friendid']?: 'empty';
于 2012-02-05T23:18:42.430 回答
6

目前您正在使用三元运算符:

$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']先前设置的值。

于 2009-08-08T14:15:09.403 回答
4

这个问题的最佳解决方案是empty() ,即如果您还需要“检查空字符串” 。

$friendid = empty($_GET['friendid']) ? 'empty' : $_GET['friendid'];

empty()不仅检查变量是否已设置,而且如果输入任何可能被视为“空”的内容,例如空字符串、空数组、整数 0、布尔值 false,则返回 false ......

于 2011-05-05T22:29:36.313 回答
1

从您对 Philippe 的回复中,我认为您需要看看emptyisset之间的区别。

总而言之,isset()如果变量存在,将返回布尔值 TRUE。因此,如果你要

$fid = $_GET['friendid'] = "";
$exists = isset($fid);

$exists将是 TRUE$_GET['friendid']存在。如果这不是你想要的,我建议你看看空。Empty 将在空字符串 ("") 上返回 TRUE,这似乎是您所期望的。如果您确实使用空,参阅我链接到的文档,还有其他情况下空会在您可能不期望的情况下返回 true,这些情况在上面的链接中明确记录。

于 2009-08-08T13:56:49.660 回答
1

我在这样的条件下使用Null 合并运算符运算符

if($myArr['user'] ?? false){

这相当于

if(isset($myArr['user']) && $myArr['user']){
于 2017-10-26T12:18:05.397 回答
0

如果没有设置friendid,则friendid =friendid否则friendid =空

于 2009-08-08T13:25:54.647 回答
0

好的,我可能遇到了类似的问题,不熟悉!像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 )。

我发现将字符串和变量都作为字符串使用有时非常令人生畏。即使在困惑中,我实际上也能理解为什么……只是让事情对我来说有点难以理解。

于 2014-03-19T08:55:09.060 回答