Skip to content
Advertisement

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.

Advertisement

Answer

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);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement