Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop between only 3 values

Tags:

loops

php

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
like image 565
markb Avatar asked Jun 06 '26 21:06

markb


1 Answers

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

like image 81
Juan Ignacio Pérez Sacristán Avatar answered Jun 09 '26 14:06

Juan Ignacio Pérez Sacristán



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!