PHP loop increment randomly?

戏子无情 提交于 2019-12-02 15:51:22

问题


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?


回答1:


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




回答2:


In one line:

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



回答3:


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

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


来源:https://stackoverflow.com/questions/10131966/php-loop-increment-randomly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!