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

8 Years
Discussion Span
Last Post by rajesh_kanna

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



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

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

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

Votes + Comments
You are supposed to guide the poster to get to the answer, and not post it yourself
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.