简体   繁体   中英

PHP loop increment randomly?

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 each time it loops?

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()

一行:

for ($i = 1; $i < 1000; $i += rand(1, 5)) echo $i;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM