php中的一行if语句

and*_*rew 14 php if-statement

我想要一些类似于javascripts的东西

    var foo = true;
    foo && doSometing();
Run Code Online (Sandbox Code Playgroud)

但这似乎不适用于PHP.

如果条件满足,我正在尝试向标签添加一个类,并且为了便于阅读,我宁愿保持嵌入式php的最小化.

到目前为止我有:

 <?php $redText='redtext ';?>
 <label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
 <input name="_name" value="<?php echo $requestVars->_name; ?>"/>
Run Code Online (Sandbox Code Playgroud)

但即使这样,思想也在抱怨我有一个带括号的if语句.

san*_*eev 28

使用三元运算符?:

改变这一点

<?php if ($requestVars->_name=='')echo $redText;?>
Run Code Online (Sandbox Code Playgroud)

   <?php echo ($requestVars->_name=='')?$redText:'';?>
Run Code Online (Sandbox Code Playgroud)

简而言之

 // (Condition)?(thing's to do if condition true):(thing's to do if condition false);
Run Code Online (Sandbox Code Playgroud)

  • 简短版本称为三元运算符 (4认同)

ceu*_*ben 10

像这样的东西?

($var > 2 ? echo "greater" : echo "smaller")
Run Code Online (Sandbox Code Playgroud)

  • 为什么要重复 echo 2 次? (4认同)

小智 7

使用示例

以下是三元运算符的更多用法,从简单到高级:

基本用法:

$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');
Run Code Online (Sandbox Code Playgroud)

速记用法:

$message = 'Hello '.($user->get('first_name') ?: 'Guest');
Run Code Online (Sandbox Code Playgroud)

回声内联

echo 'Based on your score, you are a ',($score > 10 ? 'genius' : 'nobody');
Run Code Online (Sandbox Code Playgroud)

有点强硬

$score = 10;
$age = 20;
echo 'Taking into account your age and score, you are: ',($age > 10 ? ($score < 80 ? 'behind' : 'above average') : ($score < 50 ? 'behind' : 'above average')); // returns 'You are behind'
Run Code Online (Sandbox Code Playgroud)

复杂程度

 $days = ($month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year %400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31)); //returns days in the given month
Run Code Online (Sandbox Code Playgroud)

要了解有关三元运算符和用法的更多信息,请访问 PHP.net Comparison Operators此处


小智 5

您可以使用三元运算符逻辑 三元运算符逻辑是使用“(条件)?(真实返回值):(错误返回值)”语句来缩短if / else结构的过程。即

/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
Run Code Online (Sandbox Code Playgroud)


Gus*_*Gil 5

我喜欢使用简约的 PHP 文本输出语法:

HTML stuff <?= $some_string ?> HTML stuff
Run Code Online (Sandbox Code Playgroud)

(这与使用 的作用相同<?php echo $some_string; ?>

您还可以使用三元运算符:

//(condition) ? (do_something_when_true) : (do_something_when_false);
($my_var == true) ? "It's true" : "It's false ;
Run Code Online (Sandbox Code Playgroud)

结局是这样的:

<?= ($requestVars->_name=='') ? $redText : '' ?>
Run Code Online (Sandbox Code Playgroud)