Reputation: 9909
I need to get a random number that is between
0 - 80
and
120 - 200
I can do
$n1 = rand(0, 80);
$n2 = rand(120, 200);
But then I need to choose between n1
and n2
. Cannot do
$n3 = rand($n1, $n2)
as this may give me a number between 80 - 120
which I need to avoid.
How to solve this?
Upvotes: 5
Views: 5215
Reputation: 358
get two random numbers $n1 and $n2
$n1 = rand(0, 80); $n2 = rand(120, 200);
define new array called $n3
$n3=array();
add $n1 and $n2 into array $n3 use array_push() function
array_push($n3,$n1,$n2);
use array_rand() function to find random index $find_index from array $n3.
$find_index=array_rand($n3,1);
show the result
echo $n3[$find_index];
Upvotes: 1
Reputation: 219
PHP has a new function for this as well called range. Very easy to use, and can be located in the PHP Manual.
It allows you to input a minimum/maximum number to grab a range from.
<?php
echo range(0, 1000);
?
Technically though, you could also enter your own two numbers to serve as the number range.
Upvotes: 1
Reputation: 9349
Since both ranges have different sizes (even if only by 1 number), to ensure good random spread, you need to do this:
$random = rand( 0, 200 - 39 );
if ($random>=120-39) $random+=39;
Fastest method. :)
The way this works is by pretending it's a single range, and if it ends up picking a number above the first range, we increase it to fit within the second range. This ensures perfect spread.
Upvotes: 8
Reputation: 318518
Since both ranges have the same size you can simply use rand(0, 1)
to determine which range to use.
$n = rand(0, 1) ? rand(0, 80) : rand(120, 200);
Upvotes: 5