Efe
Efe

Reputation: 954

Adding a class to the last listed item

I list the latest 5 events on one section of my website. And every time an item is listed, it has a divider at the bottom. I want to add last to the last <li> so that the divider will disappear on the last item.

So I changed <li class="clearfix"> to <li class="clearfix last">. How can I do it?

FYI, <?php $iCounterLi++; ($iCounterLi==5)? 'last':''; ?> wont work because I may have less than 5 upcoming events from time to time.

Thanks!

<?php
  $get_latest_events = get_latest_events(5);
  if(count($get_latest_events) > 0) {
    foreach($get_latest_events as $eventdata) {
      $entity_data = node_load($eventdata->entity_id);
      $event_start_date = check_isset_start_date($entity_data,'event_calendar_date','und');
      if($event_start_date !='') {
        $explode_event_date = explode(" ",$event_start_date);
        $explode_event_day = strtotime($explode_event_date[0]);
        $explode_event_time = $explode_event_date[1];
        $event_start_day1 = strftime("%B",$explode_event_day);
        $event_start_day2 = strftime("%d",$explode_event_day);
      }
      $location = check_isset($entity_data,'field_location','und');
    ?>
    <li class="clearfix"></li>

Upvotes: 0

Views: 65

Answers (2)

Dylan
Dylan

Reputation: 412

If you really want to use PHP, you can check to see if the count() matches the current $count.

$arr = array("bob","henry","sam");

$arrCount = count($arr);  // 3

$count = 0;

echo '<ul>';

foreach($arr AS $k => $v){

   $count++;

   if($count == $arrCount)
      echo '<li class="last">';
   else
      echo '<li>';

   echo $v;

   echo '</li>';
}

echo '</ul>';

Alternatively, you can set the internal pointer of the array to the final element using end() and then look for it while you loop through.

$arr = array("bob","henry","sam");

$arrEnd = end($arr);  // "sam"


echo '<ul>';

foreach($arr AS $k => $v){

   if($v == $arrEnd)
      echo '<li class="last">';
   else
      echo '<li>';

   echo $v;

   echo '</li>';
}

echo '</ul>';

Upvotes: 2

gberger
gberger

Reputation: 2863

You don't need a class for that; you can select the last element in CSS by doing something like:

ul li:last-child

Upvotes: 0

Related Questions