How to display random numbers in a given range from 1 to 90, that is, numbers should be displayed without repetitions, and all 90, but in random order.

    1 answer 1

    Option 1:

    $used = array(); while (count($used)<90){ $rand = mt_rand(1,90); if (!in_array($rand,$used)) { $used[] = $rand; echo $rand."<br />"; } } 

    Option 2 (better):

     for ($i=1;$i<=90;$i++) $arr[]=$i; while (count($arr)>0){ shuffle($arr); echo array_pop($arr)."<br />"; } 

    The 2nd is better than the first, because in the first, the number of loop iterations depends on how often the mt_rand will fall into the unused number. Therefore, if we have already deduced 10, and the random number has given out 10 more times, then as a result, 50 extra iterations. And in the second variant, the number of iterations is equal to the number of output numbers.

    Option 3 (from @ikoolik + from me) removed the loop in the filling:

     $arr = range(1,90); shuffle($arr); foreach ($arr as $val) echo $val."<br />"; 
    • The first option is terrible, remove it =) - Zowie
    • one
      Terrible - not terrible, it does not matter. The main thing works =) About the fact that he wrote badly, because to use it or not - this is already a business. ) - DemoS
    • one
      you can still in the second version instead of while loop use shuffle ($ arr); foreach ($ arr as $ num) {echo $ num; } so we can continue to use our array. Tell me how you can highlight the code in the comments? - ikoolik
    • one
      In your version the numbers will be repeated, which is unacceptable for the task. > tell me how you can highlight the code in the comments? Before each line there are 4 spaces - DemoS