-1

How can I create a loop or limit for random number generation? I need 30 random numbers from (0,100).

I know I can use rand(0,100), for general generation of numbers. But I need to make this happen 30 times before I can sort out the data.

Repetition of numbers is NO issue, but I also need to sort the values into x<50 and x>50. Any idea how I can pull numbers from the array into 2 separate groups once generated?

Kari
  • 115
  • 1
  • 1
  • 10
  • https://stackoverflow.com/questions/5612656/generating-unique-random-numbers-within-a-range-php –  Sep 20 '18 at 03:44

1 Answers1

0

Try this:

$lessFifty = array(); // Array to hold less than fifty numbers
$moreFifty = array(); // Array to hold more than fifty numbers

for ($i = 1; $i<=30; $i++) {
        $number = rand(0, 100); // Variable $number holds random number

        // Conditional statements
        if ($number < 50 ) { // Check if value is less than fifty 
            $lessFifty[] = $number; // Add number to this array
        } else { // Check if value is greater than fifty
            $moreFifty[] = $number; // Add number to this array
        }
}

// Display numbers in arrays
print_r($lessFifty);
print_r($moreFifty);

The for loop will will run the rand() function 30 times and insert each random number generated into the array $randomNum.

You can also use the while or do while loop to do the same action. It is up to you.

bastien
  • 414
  • 7
  • 14
  • That's perfect, and how would I pull out an individual number from the array to test it against something else? For example, say I want to pick which numbers are less than 20. How do I pull them to test them against that parameter and where would I store them? – Kari Sep 20 '18 at 17:08
  • I updated my code and added comments inside the code based on your edited question. To pull out an individual number you should do `$lessFifty[0]` where `$lessFifty` is the array and `[0]` the index of the value in the array. – bastien Sep 20 '18 at 19:04