Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One line if statement in PHP

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.

like image 480
andrew Avatar asked Jan 12 '14 17:01

andrew


People also ask

What is if condition in PHP?

In PHP we have the following conditional statements: if statement - executes some code if one condition is true. if...else statement - executes some code if a condition is true and another code if that condition is false. if... elseif...else statement - executes different codes for more than two conditions.

What is ternary operator in PHP?

The term "ternary operator" refers to an operator that operates on three operands. An operand is a concept that refers to the parts of an expression that it needs. The ternary operator in PHP is the only one that needs three operands: a condition, a true result, and a false result.

How many conditional statements are there in PHP?

In PHP, there are 4 different types of Conditional Statements.


Video Answer


1 Answers

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); 
like image 136
sanjeev Avatar answered Sep 25 '22 16:09

sanjeev