954,576 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

PHP random number check

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

rajeesh_rsn
Posting Whiz in Training
265 posts since Sep 2008
Reputation Points: 10
Solved Threads: 0
 

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

tuse
Junior Poster
173 posts since Jul 2007
Reputation Points: 32
Solved Threads: 14
 

This code will help you in retrieving 15 random numbers and storing them in an array,.....

<?php 
 $j = 0;
 $data = array();
 while($j < 15)
 {
  $value = rand(2,88);
  if(!(in_array($value,$data))) 
  { $j = $j + 1;
  $data[$j] = $value; }
 }
foreach($data as $keys)
{ echo $keys.""; }
 ?>


You use this code to get 15 random numbers and you code to select 10 nums as you wish,..

rajesh_kanna
Newbie Poster
4 posts since Aug 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You