One line if statement in PHP

if-statement, php

Solution

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

Problem

I'd like to to some thing similar to JavaScript's ``` var foo = true; foo && doSometing(); ``` but this doesn't 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 to 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 without braces.

Original source