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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.