2

im trying to get data from the database and list them in a <li> list. im trying to find out each third list item and give it a diffrent li class? this is my code

<?php
while ($row = mysql_fetch_array($getupdates)){
?>
<li id="update" class="group">
   blah blah blah
</li>
<?php } ?>

so basically for every third item i want to give it a different li class

<li id="update" class="group third">
2
  • 3
    as a general rule of thumb, never use shorttags ( <? or <= instead of <?php . They're deprecated and will be turned off on some servers Commented Jan 28, 2011 at 23:01
  • @phihag that is a silly rumor, short tags are not going anywhere. Commented Jan 29, 2011 at 0:36

5 Answers 5

10

Have a counter in your while loop. Let's call it $i. In your loop, add this:

$i++;
if ($i % 3 == 0) {
   //do something you'd do for the third item
}
else { //default behavior }
Sign up to request clarification or add additional context in comments.

1 Comment

i you need an counter you could use an for loop: for($i=0;$row = mysql_fetch_array($getupdates);$i+). But it does not really matter
2

You could do this a lot easier using CSS3 pseudo-class attribute selectors. Something like this:

li:nth-child(3) {
  font-weight: bold;
}

If you're worried about IE support of CSS3 attributes, you can easily add support with a polyfill like http://selectivizr.com/

Comments

1

Use a counter, and then just check if modulo 3 of the counter is 0 or not to determine if it's a third row.

<?php
$rowCount = 0;
while ($row = mysql_fetch_array($getupdates))
{
    $useDiffClass = (($rowCount++ % 3) == 0);    
    ?>
    <li id="update" class="group <?=($useDiffClass ? "third" : "");?>">
        blah blah blah
    <li>
    <?
}
?>

Comments

0
<?php
$i = 0;
while (($row = mysql_fetch_array($getupdates)) !== false){
   echo '<li id="update" class="group';
   if ($i++ % 3 == 2) echo ' third';
   echo '">blah blah blah</li>';
}

Comments

0

Modulus operator is the way to go.

But you may also use CSS3 attributes to achieve the same effect without using PHP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.