I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
  echo '<div class="result">';
  echo $fp['project_name'];
  echo '</div>';
}
?>
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
    // reset the variable
    $class = '';
    // on every third result, set the variable value
    if(++$counter % 3 === 0) {
        $class = ' third';
    }
    // your code with the variable that holds the desirable CSS class name
    echo '<div class="result' . $class . '">';
    echo $fp['project_name'];
    echo '</div>';
}
?>
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With