Looping in threes


#1

Hi.

Is looping like this possible?

Let’s say I have an array containing days of the week. I need to display the days in groups of three (as the CSS is not the same for every element, I can’t simply foreach the array, one element at a time). The number of elements in the array will be unknown and almost certainly not a multiple of three.

I need output like:

on iteration 1, I need
Monday
Tuesday
Wednesday

iteration 2
Thursday
Friday
Saturday

iteration 3
Sunday

I’m thinking a For loop with Step 3 then using i, i+1 and i+2 each time but For requires a specified number of elements/iterations…

Cheers.


#2

Well no, For requires a stop condition. Not a fixed number. $i < length of the array is a perfectly valid stop condition.

There are several ways to go about such a loop;
you could… foreach, and stick a check for if the modulo of the index and 3 is 0, to stick an element in
you could while, though that’ll end up looking at lot like a for loop really…
you could incorporate some array_slices, though that gets tricky with leftovers.


#3

m_hutley,

Cheers, buddy. Modulo: that’s the key. I can do this, which then allows me to use a single output instead of groups of three:

for ($i=1; $i<count($arrayName); $i++)
{
    echo '<li'.($i % 3 == 0 ? ' class="my-odd-class"' : '').'>'.$arrayName[$i].'</li>';
}

Thank you for pointing me in the right direction. :grinning:


#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.