PHP random number check

Reply

Join Date: Sep 2008
Posts: 138
Reputation: rajeesh_rsn is an unknown quantity at this point 
Solved Threads: 0
rajeesh_rsn rajeesh_rsn is offline Offline
Junior Poster

PHP random number check

 
0
  #1
Aug 8th, 2009
Hai,

I had a small doubt in my php script.
I need to select 10 random numbers from a range ( for eg: 2-88) and stored it in an array.
For eg:
$number=rand(2,88); This returns only one value from the range 2-88. I need 15 random numbers from the given range and also I need 15 different numbers and finally stored it in an array. ie $number[1],$number[2] .......

Please help me .... Thanks in Advance
Rajeesh
Reply With Quote Quick reply to this message  
Join Date: Jul 2007
Posts: 169
Reputation: tuse is an unknown quantity at this point 
Solved Threads: 14
tuse's Avatar
tuse tuse is offline Offline
Junior Poster

Re: PHP random number check

 
0
  #2
Aug 8th, 2009
1. Keep an array to hold the random numbers

2. In order to add an element to this array, generate a random number in the required range, and check the array to see if the generated number is already a part of the array (using foreach)

3. If the generated random number is not a part of the array, append it to the array, else goto step 2.

4. Finish the algorithm when the array holds 15 elements

----

Alternatively, you can use 'in_array()' to check if a value exists in an array

http://www.w3schools.com/PHP/func_array_in_array.asp
My blog on .NET- http://dotnet.tekyt.info
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 4
Reputation: rajesh_kanna is an unknown quantity at this point 
Solved Threads: 0
rajesh_kanna rajesh_kanna is offline Offline
Newbie Poster

Re: PHP random number check

 
-1
  #3
Aug 8th, 2009
This code will help you in retrieving 15 random numbers and storing them in an array,.....

  1. <?php
  2. $j = 0;
  3. $data = array();
  4. while($j < 15)
  5. {
  6. $value = rand(2,88);
  7. if(!(in_array($value,$data)))
  8. { $j = $j + 1;
  9. $data[$j] = $value; }
  10. }
  11. foreach($data as $keys)
  12. { echo $keys."<br>"; }
  13. ?>

You use this code to get 15 random numbers and you code to select 10 nums as you wish,..
Last edited by peter_budo; Aug 9th, 2009 at 8:23 am. Reason: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC