One line if statement in PHP One line if statement in PHP php php

One line if statement in PHP


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


You can use Ternary operator logicTernary 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


Something like this?

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