I have this code:
<div id="menu">
<ul>
<li><span id="menulabel">Your Languages</span></li>
<?php
$hotClass = '';
$newClass = '';
$topClass = '';
if ($sort == 'hot')
$hotClass = 'active';
else if ($sort == 'new')
$newClass = 'active';
else if ($sort == 'top')
$topClass = 'active';
?>
<li><a id="Hot" href="index.php?sort=hot&page=1" class="<?php echo $hotClass; ?>">Hot</a></li>
<li><a id="New" href="index.php?sort=new&page=1" class="<?php echo $newClass; ?>">New</a></li>
<li><a id="Top" href="index.php?sort=top&page=1" class="<?php echo $topClass; ?>">Top</a></li>
</ul>
</div>
Depending on which sorting the page is using a different menu item is highlighted to show the user. However, I really dislike this code because the class is empty instead of not present when the list item is not active. Also, every if statement does basically the same thing. Is it possible to refactor this in to something more elegant and readable? Thanks.
You might consider using a ternary here…
definitely saves a lot of code
In case you’re not familiar with the Ternary Operator
EDIT
As Matijs Points out
you could even put the entire class declaration inside the operator to avoid ending up with
class=""