One line if statement in PHP

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

Solution 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

Solution 3:

Something like this?

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

Solution 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

Solution 5:

I like to use the minimalist PHP text output syntax:

HTML stuff <?= $some_string ?> HTML stuff

(This works the same as using an <?php echo $some_string; ?>)

You can also use the ternary operator:

//(condition) ? (do_something_when_true) : (do_something_when_false);
($my_var == true) ? "It's true" : "It's false ;

Ending up like this:

<?= ($requestVars->_name=='') ? $redText : '' ?>