Skip to content Skip to sidebar Skip to footer

Putting Inline Style Using Ternary Operator Php

I am trying to add css inline style based on a php variable's value. I tried doing so with ternary operator, and also I converted the variable value to float. But the css is not be

Solution 1:

You're missing the echo command prior to the condition. Basically if the condition returns true or false, the statements are being returned and not necessary being echoed.

<?phpecho ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"?>

Sidenote, A better practice:

Since both of the returned strings are style, there's no point in repeating it (developers are lazy :] ). So you can simply write:

<tdstyle='background-color: <?phpecho ($leaveBalance < 0) ? "red" : "green"?>'>

Solution 2:

Not

<?php 
    ($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"?>

but

<?phpecho (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'");
?>

or

<?= (($leaveBalance < 0) ? "style='background-color:red;'" : "style='background-color:green;'"); ?>

Post a Comment for "Putting Inline Style Using Ternary Operator Php"