PHP: loop 1 to 5 starting at 3

I want to use a loop from 1 to 5. This is easy if you use a for loop:

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

But imagine instead of starting with $ i = 1. I have a random starting number from 1 to 5, and this time its value is 3. Therefore, I need to start the cycle with 3, and the sequence of cycles should be: 3, 4, 5,1,2

I already have a radiometer number, let's say it's 3, then I need 3 4 5 1 2 .. If it were 5, I would need 5 1 2 3 4

How can i do this?

Thank you so much!

+5
source share
5 answers

Try the following:

for ($i = 0, $j = 3; $i < 5; $i++)
{
   echo $j;
   $j %= 5;
   $j++;
}

You need two vars to do what you want. If you set J = 3, it will do 3 4 5 1 2

enjoy.

+1
source

(), 5:

$offset = rand(1,5);
for ($i=1; $i<=5; $i++)
{
  echo (($i + $offset ) % 5) + 1;
}
+5

, $i 1 5, , $j, $i + 2, , , :

3, 4, 5, 6, 7

(%), :

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

1 5 2 (3-7) mod(5), :

:

$j = ($i + 2) % 5

3, 4, 0, 1, 2

, , . , 2, 1 :

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

3, 4, 5, 1, 2.

, , 5 :

//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;
}
+2

( ):

, 5 , . 0 4:

for ($i = 0; $i < 5; $i++) { ...

. , 1 5:

for ($i = 0, $j = 1; $i < 5; $i++, $j++) { ...
             ^^^^^^                ^^^^

$i - , $j , .

, , , .

, $j 5, , reset 1. modulo. , $j , 5. modulo, % PHP:

for ($i = 0, $j = 3; $i < 5; $i++, $j %= 5, $j++) { ...
                                   ^^^^^^^

for, .

In this example, you can replace 3with your random starting number. Make sure that it is greater than 0 and lower than 6, otherwise at least the first iteration will give you the wrong number.

As you can imagine, there are several ways to do this, so this is just one example.

+1
source
 $i = array(3,4,5,1,2); //considering you want to follow this order, and not random.
 foreach($i as $v) {
 //do something
 }
0
source

All Articles