Reputation: 1189
I have a for loop, and I want to write a function to abstract the following sequence:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
.............
So, in a somewhat "pseudo" code, the function would have to check multiples like so:
$i = 0;
for (condition) {
$i++
if ($i is 1, 5, 9, 13) do something
if ($i is 2, 6, 10, 14) do something
if ($i is 3, 7, 11, 15) do something
if ($i is 4, 8, 12, 16) do something
}
Any ideas?
Upvotes: 1
Views: 53
Reputation: 23255
Use the modulo operator. 1, 5, 9 or 13 modulo 4 is always 1.
Also you may want to use a switch / case statement, to avoid repeating the modulo 4 part.
<?php
switch ($remainder = $i % 4) {
case 0:
// and do another thing too
break;
case 1:
// do something
break;
case 2:
// do something else
break;
case 3:
// do yet another thing
break;
default:
throw new \UnexpectedValueException(sprintf(
'the remainder is %d, this is very strange!',
$remainder
));
}
Upvotes: 1