How to repeat an output until the last row then assign a different style to it?

Hey guys, bascially I’m developing a simple news script, and part of it has a “quick news” section, which will display the latest 3 (or any number I want) news items, each seperated by a line (


in the example below).

What I want to acheive is the top 2 news items have a set LI class assigned to them, and then the 3rd LI in the list to have a different style attached to it (one without a bottom border basically), so it’ll bascially repeate out the normal

  • until it hits the last item to be output, at which point it uses a LI with a class attached to it.

    What I don’t know how to do, is tell the PHP that once it’s out putted 2 LI’s, then the 3rd LI is to have a different class on it.

    eg

    [code]

  • News Item 1
  • News Item 2
  • News Item 3
  • [/code]

    I’m pretty new to PHP so not sure how to achieve this and would appreicate any help you can offer.

    Here’s my code so far…

    [code]<?php
    $latestnews_sql = “SELECT * FROM news ORDER BY date DESC LIMIT 3”;
    $latestnews_query = mysql_query($latestnews_sql) or die (mysql_error());
    $list_latestnews = mysql_fetch_assoc ($latestnews_query);
    ?>

      <?php do { ?>
    • <?php echo $list_latestnews['title']; ?>

      <?php echo substr($list_latestnews['body'],0,80)."...";?> view more

      <?php echo $list_latestnews['author']; ?> - <?php echo date("l, jS F Y", strtotime($list_latestnews['date'])); ?>


    • <?php } while ($list_latestnews = mysql_fetch_assoc ($latestnews_query)) ?>
    [/code]

    add this line into your ‘do’ statement immediatley after the opening bracket:
    [php]if($row[‘ID’] == 2) { $li = ‘

  • ’; } else { $li = ‘
  • ’; }[/php]
    then replace
  • in your script for [php]<?php echo $li; ?>[/php] that should work.

    :wink:

  • ok, my mistake:
    [php]if($row[‘ID’] == 2) { $li = ‘

  • ’; } else { $li = ‘
  • ’; }[/php]
    should be
    [php]if($list_latestnews[‘ID’] == 2) { $li = ‘
  • ’; } else { $li = ‘
  • ’; }[/php]
  • Thanks Redscouse, that looks like just what I need.

    However, where you have [php]if($list_latestnews[‘ID’] == 2)[/php] this is looking for a news item with an ID of 2, however in my quick news, this will change as more news is added (in my example the bottom of the 3 news items is actually ID=34

    Is there a way to change this from looking for ID==2 and change it to look for the 2nd output value instead?

    Aha!

    I have managed to acheive this using the following jQuery

    $("ul#quicknews li:last-child").addClass("last");

    Thanks for all your help guys.

    you could also of used
    [php]
    $count = count($list_latestnews);
    if($list_latestnews[‘ID’] == $count)
    [/php]

    Glad you got it working :wink:

    Sponsor our Newsletter | Privacy Policy | Terms of Service