如果为null,则在PHP的一行中使用其他变量 [英] If null use other variable in one line in PHP
问题描述
PHP中是否存在类似于JavaScript的内容:
Is there in PHP something similar to JavaScript's:
alert(test || 'Hello');
因此,当test未定义或为null时,我们将看到Hello,否则-我们将看到test的值.
So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.
我在PHP中尝试了类似的语法,但是它似乎无法正常工作...而且我也不知道如何用Google搜索这个问题.
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..
谢谢
修改
我可能应该补充一点,我想在数组中使用它:
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.
$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
推荐答案
有关PHP7解决方案,请参见下面的@Yamiko答案 https://stackoverflow.com/a/29217577/140413
See @Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
或者您可以变得更加健壮并执行此操作
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
这篇关于如果为null,则在PHP的一行中使用其他变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!