putting inline style using ternary operator php

吃可爱长大的小学妹 提交于 2020-05-30 09:37:11

问题


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 being applied as expected.

       <tbody>
        <?php
        $totalLeaveTaken = 0.00;
        $totalBalance = 0.00;
            foreach ($GetEmployeeLeaveBalance as $member):
                $totalLeaveTaken += $member['usedDays'];
                $totalBalance += $member['Remaining_Leave_Days'];
                $leaveBalance = floatval($member['Remaining_Leave_Days']);
            ?>
            <tr>
                <td><?php echo $member['title']; ?></td>
                <td><?php echo $member['maxDays']; ?></td>
                <td><?php echo $member['usedDays']; ?></td>
                <!-- <td><?php echo gettype($leaveBalance);?></td> -->
                <td
                <?php 
                ($leaveBalance < 0) ? 
                "style='background-color:red;'" : "style='background-color:green;'"
                ?>
                >
                <?php echo $member['Remaining_Leave_Days']; ?>    
                </td>
            </tr>
        <?php endforeach; ?>
        <tr>
            <td></td>
            <td></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo number_format($totalLeaveTaken, 2); ?></td>
            <td style="background-color: #33CCFF; font-weight: bold;">Total: <?php echo 
            number_format($totalBalance, 2); ?></td>
        </tr>
        </tbody>

But the simple inline styling is working fine.


回答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.

<?php
echo ($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:

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



回答2:


Not

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

but

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

or

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


来源:https://stackoverflow.com/questions/47326510/putting-inline-style-using-ternary-operator-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!