Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to output a value on every third result of a foreach statement in php?

Tags:

foreach

php

echo

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>';
}

?>

I would like to:

On every third result, give the div a different class. How can I achieve this?

like image 204
hairynuggets Avatar asked May 04 '12 08:05

hairynuggets


1 Answers

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>';
}

?>
like image 144
Treffynnon Avatar answered Oct 04 '22 07:10

Treffynnon