PHP loop increment randomly?

前端 未结 3 482
难免孤独
难免孤独 2021-01-28 11:43

We all know the basic

$i = 1;

while ($i<100){
    echo $i;
    $i++
}

Question: How do I increment $i by a random number between 1 and 5 e

相关标签:
3条回答
  • 2021-01-28 12:02

    Exactly like you described it in words: By increment it with a random number between 1 and 5.

    while ($i < 1000) {
      echo $i;
      $i += rand(1,5);
    }
    

    rand()

    0 讨论(0)
  • 2021-01-28 12:20

    In one line:

    for ($i = 1; $i < 1000; $i += rand(1, 5)) echo $i;
    
    0 讨论(0)
  • 2021-01-28 12:20

    mt_rand is faster and uses uses the Mersenne Twister algorythm (1997)

    while ($i < 1000) {
      echo $i;
      $i += mt_rand(1,5);
    }
    
    0 讨论(0)
提交回复
热议问题