如果 null 在 PHP 中的一行中使用其他变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4998178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:30:32  来源:igfitidea点击:

If null use other variable in one line in PHP

php

提问by rochal

Is there in PHP something similar to JavaScript's:

PHP 中是否有类似于 JavaScript 的东西:

alert(test || 'Hello');

So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.

因此,当 test 为 undefined 或 null 时,我们将看到 Hello,否则 - 我们将看到 test 的值。

I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..

我在 PHP 中尝试了类似的语法,但它似乎没有正常工作......而且我不知道如何用谷歌搜索这个问题......

thanks

谢谢

Edit

编辑

I should probably add that I wanted to use it inside an array:

我应该补充一点,我想在数组中使用它:

$arr = array($one || 'one?', $two || 'two?'); //This is wrong

But indeed, I can use the inline '? :' if statement here as well, thanks.

但确实,我可以使用内联 '? :' if 声明也在这里,谢谢。

$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK

采纳答案by Jeff Busby

See @Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413

有关 PHP7 解决方案https://stackoverflow.com/a/29217577/140413,请参阅下面@Yamiko 的回答

 echo (!$test) ? 'hello' : $test;

Or you can be a little more robust and do this

或者你可以更健壮一点,然后这样做

echo isset($test) ? $test : 'hello'; 

回答by Yamiko

you can do echo $test ?: 'hello';

你可以做 echo $test ?: 'hello';

This will echo $testif it is true and 'hello'otherwise.

$test如果它是真的,'hello'否则这将回显。

Noteit will throw a notice or strict error if $testis not set but...

请注意,如果$test未设置,它将抛出通知或严格错误,但...

This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.

这应该不是问题,因为大多数服务器都设置为忽略这些错误。大多数框架都有触发这些错误的代码。



Edit:This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.

编辑:这是一个经典的三元运算符,但省略了中间部分。自 PHP 5.3 起可用。

echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello';        // as this one

This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICEerror. For the latter, check the PHP7 answer below (soon hopefully above).

这仅检查第一个变量的真实性,而不检查它是否未定义,在这种情况下它会触发E_NOTICE错误。对于后者,请检查下面的 PHP7 答案(希望很快在上面)。

回答by Yamiko

From PHP 7 onwards you can use something called a coalesce operatorwhich does exactly what you want without the E_NOTICE that ?:triggers.

从 PHP 7 开始,您可以使用称为合并运算符的东西,它可以在没有?:触发E_NOTICE 的情况下执行您想要的操作

To use it you use ??which will check if the value on the left is set and not null.

要使用它,您可以使用??which 将检查左侧的值是否已设置且不为空。

$arr = array($one ?? 'one?', $two ?? 'two?'); 

回答by TrophyGeek

One-liner. Super readable, works for regular variables, arrays and objects.

单行。超级可读,适用于常规变量、数组和对象。

// standard variable string
$result = @$var_str ?: "default";

// missing array element
$result = @$var_arr["missing"] ?: "default";

// missing object member
$result = @$var_obj->missing ?: "default";

See it in action: Php Sandbox Demo

看到它在行动:Php Sandbox Demo

回答by Arth

I'm very surprised this isn't suggested in the other answers:

我很惊讶其他答案中没有建议这样做:

echo isset($test) ? $test : 'hello';

From the docsisset($var)will return falseif $vardoesn't exist or is set to null.

如果不存在或设置为 null ,则文档isset($var)中将返回false$var

The null coalesce operator from PHP 7 onwards, described by @Yamiko, is a syntax shortcut for the above.

从 PHP 7 开始,由 @Yamiko 描述的 null 合并运算符是上述语法的快捷方式。

In this case:

在这种情况下:

echo $test ?? 'hello'; 

回答by Felix Kling

If you want to create an array this way, array_mapprovides a more concise way to do this (depending on the number of elements in the array):

如果要以这种方式创建数组,请array_map提供一种更简洁的方法来执行此操作(取决于数组中的元素数量):

function defined_map($value, $default) {
    return (!isset($value) || is_null($value)) ? $default : $value;
    // or return $value ? $default : $value;
}

$values = array($one, $two);
$defaults = array('one', 'two');

$values = array_map('defined_map', $values, $defaults);

Just make sure you know which elements evaluate to falseso you can apply the right test.

只需确保您知道评估哪些元素,false以便您可以应用正确的测试。

回答by Sean Walsh

There may be a better way, but this is the first thing that came to my mind:

可能有更好的方法,但这是我想到的第一件事:

 echo (!$test) ? "Hello" : $test;

回答by AndrewKS

Null is false in PHP, therefore you can use ternary:

在 PHP 中 Null 为 false,因此您可以使用三元:

alert($test ? $test : 'Hello');

Edit:

编辑:

This also holds for an empty string, since ternary uses the '===' equality rather than '=='

这也适用于空字符串,因为三元使用 '===' 相等而不是 '=='

And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.

无论使用 '===' 还是 '==' 运算符,空字符串或空字符串都是假的。我真的应该先测试我的答案。

回答by Geoff Adams

Well, expanding that notation you supplied means you come up with:

好吧,扩展您提供的符号意味着您想出了:

if (test) {
    alert(test);
} else {
    alert('Hello');
}

So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':

所以这只是一个简单的 if...else 构造。在 PHP 中,您可以将简单的 if...else 结构缩写为“三元表达式”:

alert($test ? $test : 'Hello');

Obviously there is no equivalent to the JS alertfunction in PHP, but the construct is the same.

显然alertPHP 中没有等效于 JS 的函数,但构造是相同的。

回答by Chris Pennycuick

alert((test == null || test == undefined)?'hello':test);