如何在 PHP 中以一种易于阅读的方式回显我不知道设置或未设置的变量

How to echo a variable that I don't know is set or not in an easy to read way in PHP

只是有一个简单的问题。我想我知道答案,但我希望不是。

我希望能够回显一个我不知道是否已设置的变量。所以我想要一个未设置的默认变量,我不想先检查它是否已设置。

所以这是一个例子:

我有一个 $variable,我不知道是否已设置。

然后

echo "This is my number: " . $variable;

如果 $variable 设置为 5,我希望它打印 "This is my number: 5",如果没有设置,我希望它打印 "This is my number: 0".

我知道我可以做这样的事情:

echo "This is my number: " . ($variable? : 0);

但是我仍然收到一条通知说 $variable 未定义,即使 echo 显示正确。

我也可以这样做

if (!isset($variable)) 
{
  $variable = 0);
}
echo "This is my number: " . $variable;

但是如果我经常这样做的话,代码太多了。

null coalescing operator 是你最好的新朋友。

echo "This is my number: " . ($variable ?? 0);

空合并运算符从 PHP 7.0.0 开始可用。要在 PHP 5.3.0 之前的旧版本中使用,另一种方法是使用 isset() and the ternary operator ?:.

echo "This is my number: " . (isset($variable) ? $variable : 0);

尝试这样的事情:

echo "This is my number: " . (isset($variable) ? $variable : 0);

适用于 PHP 5+