eugeniu Posted July 18, 2008 Share Posted July 18, 2008 Let's say I want to generate 4 different random numbers from 1 to 100. How do I do that? I only know how to generate one random number... Quote Link to comment Share on other sites More sharing options...
papaface Posted July 18, 2008 Share Posted July 18, 2008 I'd do: <?php $i = 0; while ($i < 4) { echo rand(0,100) . "<br />"; $i++; } ?> or: $rand = array(rand(0,100),rand(0,100),rand(0,100),rand(0,100)); foreach ($rand as $val) { echo $val . "<br />"; } or: $rand1 = rand(0,100); $rand2 = rand(0,100); $rand3 = rand(0,100); $rand4 = rand(0,100); echo $rand1 ." ". $rand2 ." ". $rand3 ." ". $rand4; Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted July 18, 2008 Share Posted July 18, 2008 Here's one way: <?php $ary = range(1,100); shuffle($ary); $nums = array_slice($ary,0,4); echo '<pre>' . print_r($nums,true) . '</pre>'; ?> papaface: There's no guarantee that you will get 4 different numbers. Ken Quote Link to comment Share on other sites More sharing options...
GingerRobot Posted July 18, 2008 Share Posted July 18, 2008 papaface: what guarantees that those random numbers are different? Quote Link to comment Share on other sites More sharing options...
papaface Posted July 18, 2008 Share Posted July 18, 2008 papaface: what guarantees that those random numbers are different? Nothing, I suppose lol. Quote Link to comment Share on other sites More sharing options...
eugeniu Posted July 18, 2008 Author Share Posted July 18, 2008 Here's one way: <?php $ary = range(1,100); shuffle($ary); $nums = array_slice($ary,0,4); echo '<pre>' . print_r($nums,true) . '</pre>'; ?> papaface: There's no guarantee that you will get 4 different numbers. Ken Oo, thanks. Is there any way I can make each generated number a separate variable with that? Quote Link to comment Share on other sites More sharing options...
kenrbnsn Posted July 18, 2008 Share Posted July 18, 2008 <?php $ary = range(1,100); shuffle($ary); list($num1,$num2,$num3,$num4) = array_slice($ary,0,4); ?> Or you could just reference each array item. Ken Quote Link to comment Share on other sites More sharing options...
eugeniu Posted July 18, 2008 Author Share Posted July 18, 2008 Oh, thanks Ken! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.