Jump to content

Random Number Query?


Solarpitch

Recommended Posts

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 .....); 	


?>

Link to comment
https://forums.phpfreaks.com/topic/93359-random-number-query/
Share on other sites

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++;
}
}
}

Link to comment
https://forums.phpfreaks.com/topic/93359-random-number-query/#findComment-478207
Share on other sites

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;
  }

}
?>

Link to comment
https://forums.phpfreaks.com/topic/93359-random-number-query/#findComment-478237
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.