Solarpitch Posted February 27, 2008 Share Posted February 27, 2008 Hey Guys, I am looking to create an array of 10 random numbers. I am not sure how to do it but here's what I've got... <?php $num1 = $_POST['num1']; $num2 = $_POST['num2']; function random_num($n=5) { return rand(0, pow(10, $n)); } $value= array(2,5,6,8,9,1,2,4,5,1); /*-> I need these 10 numbers to be populated randomly by the function*/ /*I was trying this which I dont think is the best way of doing it....*/ $1 = echo random_num(1); $2 = echo random_num(1); $3 = echo random_num(1); $value= array($1,$2,$3 .....); ?> Quote Link to comment Share on other sites More sharing options...
haku Posted February 27, 2008 Share Posted February 27, 2008 I could type something out, but there are already so many tutorials on the net that will tell you how to do this. Google it, you'll have your answer faster than I could type it. Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 27, 2008 Share Posted February 27, 2008 I'm not really following what you are trying to accomplish, but here goes: <?php function random_num($n=5) { return rand(0, pow(10, $n)); } for ($i=0; $i<10; $i++) { $value[] = random_num(1); } ?> Quote Link to comment Share on other sites More sharing options...
Solarpitch Posted February 27, 2008 Author Share Posted February 27, 2008 Thanks mjdamato .. exactly what I was looking for. Quote Link to comment Share on other sites More sharing options...
spikeon Posted February 27, 2008 Share Posted February 27, 2008 this one will make sure that you don't, u know, have a duplicate $random = rand(0,9); will generate a random number from 0 to 9 to get those numbers, its easy as the array the keys are 0-9 $order[] = '9999' //a number you'll never use while($counter < 10){ $random = rand(0,9); foreach($order as $don){ if($don == $random){ } else{ $order[] = $random; $counter++; } } } Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 27, 2008 Share Posted February 27, 2008 Well, the OP didn't statre anything about unique numbers. But, if that's what he needs, this would be more efficient: <?php $value = array(); while(count($value) < 10){ $random = rand(0,9); if (!in_array($random, $value)) { $value[] = $random; } } ?> Quote Link to comment Share on other sites More sharing options...
spikeon Posted February 27, 2008 Share Posted February 27, 2008 ah, in_array... now that i know thats a command, i'll remember it 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.