Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: looping from 1 till 5 starting by 3

I want to loop from 1 till 5. That's easy if you use a for loop:

for ($i=1; $i<=5; $i++)
{
 // do something
}

But imagine instead of starting by $i=1 I have a random start number from 1 to 5 and this time its value is 3. So I have to start looping from 3 and the loop sequence should be: 3,4,5,1,2

I already have the radom number, let's say it is 3, then I need 3 4 5 1 2 .. if it was 5, I would be needing 5 1 2 3 4

How can I do this??

Thanks a lot!

like image 355
Adts Qdsfsd Avatar asked Sep 24 '12 13:09

Adts Qdsfsd


2 Answers

You want to start at a certain random point (the offset) and then make a loop of 5:

$offset = rand(1,5);
for ($i=1; $i<=5; $i++)
{
  echo (($i + $offset ) % 5) + 1;
}
like image 156
JvdBerg Avatar answered Oct 10 '22 02:10

JvdBerg


Well, $i will iterate from 1 to 5 which means you can make another variable $j that is equivalent to $i + 2, but of course it would result in the count of:

3, 4, 5, 6, 7

Which is where the modulus operator (%) comes in, the modulus operator gives you the remainder after division by the second number:

3 % 5 //3
7 % 5 //2

If you iterate from 1 to 5 and add 2 (3-7), and take the result mod(5), you'd get:

Equation:

$j = ($i + 2) % 5

3, 4, 0, 1, 2

This is close to what you want, but not quite. So instead of adding 2 initially, add 1 initially, and again after the result of the modulus:

$j = $i;
$j += 1;
$j %= 5;
$j += 1;
//or in one line:
$j = (($i + 1) % 5) + 1;

Which will give you a series of 3, 4, 5, 1, 2.

To use a random offset, just make sure that the initial padding is randomized in a set of 5 consecutive positive integers:

//this could be rand(0, 4) or rand(101, 105)
//it doesn't actually matter which range of 5 integers
//as the modulus operator will bound the results to the range of 0-4
$offset = rand(1, 5);
for ($i = 1; $i <= 5; $i++) {
    $j = (($i + $offset) % 5) + 1;
}
like image 23
zzzzBov Avatar answered Oct 10 '22 02:10

zzzzBov