Ahhhhhhhhhhhhhdfgbv Ahhhhhhhhhhhhhdfgbv - 2 months ago 8
PHP Question

Loop between only 3 values

I'm trying to loop a class for each

div
.

I know how to get the first and last, but can't figure out how to iterate 1-3 (or more for others who want to expand this)

What I have:

$cats = get_categories();
// default value
$i = 0;

foreach ($cats as $cat) {
// reset class
$class = '';

if(++$i % 3 == 0) { $class = 'third - '; }
elseif(++$i % 2 == 0) { $class = 'second - '; }
elseif(++$i % 1 == 0) { $class = 'first - '; }

echo $class . $cat->name;
}


However, when I echo the
$i
to see what is happening, it is adding values each time, rather than going through the if statement (which I thought would not cause it to increase the number)

I end up getting this kind of output:

third - cat01
first - cat02
second - cat03
third - cat04
second - cat05
first - cat06
third - cat07

Answer

Major problem is at $i % 2 == 0 . It should be $i % 3 == 1. You must always extract modulus 3 and check the result against 0, 1 and 2:

$cats = array('cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7');
$i = 0;
foreach ($cats as $cat) {
    if ($i % 3 == 0) { $class = ' first'; }
    elseif ($i % 3 == 1) { $class = ' second'; }
    elseif ($i % 3 == 2) { $class = ' third'; }
    $i++;
    echo "\n$class - $cat";
}

Output:

 first - cat1
 second - cat2
 third - cat3
 first - cat4
 second - cat5
 third - cat6

http://ideone.com/mljRcn

With 4 classes it works too:

http://ideone.com/fLR2nl