[php] one line if statement in php

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.

This question is related to php if-statement

The answer is


Something like this?

($var > 2 ? echo "greater" : echo "smaller")

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

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

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();