DigitalFirefly
DigitalFirefly

Reputation: 99

Generate a random number from 2 ranges of numbers in php

My current code generates 116 random numbers between the range of 34 and 76 and puts them into an array called $common.

for($i = 0; $i < 116; $i++){
    $common[] = mt_rand(34, 76);
}

Is it possible to generate a random number from 2 groups of numbers? For instance, I want to have it pick 116 random numbers between 1-22 and 34-76.

Upvotes: 1

Views: 1230

Answers (1)

AbraCadaver
AbraCadaver

Reputation: 79024

1. Here's one way:

for($i = 0; $i < 116; $i++){
    $common[] = array(mt_rand(1, 22), mt_rand(34, 76))[mt_rand(0, 1)];
}
  • Create an array of two random numbers, one from each range
  • Randomly pick array index 0 or 1

2. Well I'm bored, here's another:

$range = array_merge(range(1, 22), range(34, 76));

for($i = 0; $i < 116; $i++){
    $common[] = $range[array_rand($range)];
}
  • Create an array of the numbers in the two ranges
  • Loop and randomly select from the range

In the second example you can also use:

$common[] = $range[mt_rand(0, count($range)-1)];

3. I'm waiting for lunch so here's another, similar to the first:

for($i = 0; $i < 116; $i++){
    $common[] = mt_rand(0, 1) ? mt_rand(1, 22) : mt_rand(34, 76);
}
  • If random falsey 0 then generate from the first range
  • If random truthy 1 then generate from the second range

Upvotes: 4

Related Questions