I'm using PHP, MySQL, HTML and CSS. Depending upon value in my PHP variable I want to apply a CSS class to an
element. How should I do this? My code snippet of PHP and HTMl( element) is as follows:<?php
$e=$_POST['users']; //$e should have either employee_id or a string "All"
?>
<li><p align="center"><a href="salary_report.php">Salary Report(Individual)</a></p></li>
<li><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
Now the scenario is if $e=="All" then I have to apply a CSS class "class="active" to following
<li><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
and if not then aapply the same CSS class to the other
<li><p align="center"><a href="salary_report.php">Salary Report(Individual)</a></p></li>
My issue is how should I use a condition depending upon PHP variable and apply a specific class to an HTML element? Can anyone help me in this regard? Thanks in advance.
You could do it like this:
<li class="<?php echo $e == "all" ? 'active' : ''; ?>><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
Try with the ternary operator
like
<li class="<?php echo $e == "All" ? 'active' : ''; ?>><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
<li class="<?php echo $e == "All" ? 'active' : ''; ?>><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
You can do it by following code.
<?php
if($e=="All")
{
?>
<li class="active"><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
<?php
}else{
?>
<li class="active"><p align="center"><a href="salary_report.php">Salary Report(Individual)</a></p></li>
<?php
}
?>
I don't understand why nobody says about second <li>
. Just flip the statements to make another <li>
"active"
<?php
$e=$_POST['users'];
?>
<li<?=($e=='All'?'':' class="active"')?>><p align="center"><a href="salary_report.php">Salary Report(Individual)</a></p></li>
<li<?=($e=='All'?' class="active"':'')?>><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>
You can also approach this way.. This is for better understanding of what is doing out there.
<?php
$data = ($e == "All") ? 'active' : '';
?>
<li class="<?php echo $data; ?>"><p align="center"><a href="salary_report_combined.php">Salary Report(Combined)</a></p></li>