问题
I'd like to to some thing similar to javascripts
var foo = true;
foo && doSometing();
but this doesnt seem to work in php.
I'm trying to add a class to a label if a condition is met and I'd prefer to keep the embedded php down do a minimum for the sake of readability.
so far I've got:
<?php $redText='redtext ';?>
<label class="<?php if ($requestVars->_name=='')echo $redText;?>labellong">_name*</label>
<input name="_name" value="<?php echo $requestVars->_name; ?>"/>
but even then the ide is complaining that I have an if statement with out braces.
回答1:
use the ternary operator ?:
change this
<?php if ($requestVars->_name == '') echo $redText; ?>
with
<?php echo ($requestVars->_name == '') ? $redText : ''; ?>
In short
// (Condition)?(thing's to do if condition true):(thing's to do if condition false);
回答2:
You can use Ternary operator logic Ternary operator logic is the process of using "(condition)? (true return value) : (false return value)" statements to shorten your if/else structures. i.e
/* most basic usage */
$var = 5;
$var_is_greater_than_two = ($var > 2 ? true : false); // returns true
回答3:
Something like this?
($var > 2 ? echo "greater" : echo "smaller")
回答4:
Use ternary operator:
echo (($test == '') ? $redText : '');
echo $test == '' ? $redText : ''; //removed parenthesis
But in this case you can't use shorter reversed version because it will return bool(true)
in first condition.
echo (($test != '') ?: $redText); //this will not work properly for this case
回答5:
The provided answers are the best solution in your case, and they are what I do as well, but if your text is printed by a function or class method you could do the same as in Javascript as well
function hello(){
echo 'HELLO';
}
$print = true;
$print && hello();
来源:https://stackoverflow.com/questions/21078149/one-line-if-statement-in-php