Skip to content

Core\Random::int

Returns a random whole number between two numbers, and both numbers can be returned.

Core\Random::int(1, 6) rolls a die. It returns 1, 2, 3, 4, 5 or 6, and each one comes up equally often. When the two numbers are the same, the result is that number. The number comes from a cryptographic generator, so it is safe to use for a login code or a PIN.

The first number must not be larger than the second. If it is, the method throws an error. It does not swap the two numbers for you, because wrong bounds usually mean a bug in the calculation before the call.

Parameters

  • $minintThe lowest value the result can be.
  • $maxintThe highest value the result can be.

Return value

Returns int. An int from $min to $max. When the two are equal, the result is $min.

Errors

  • RuntimeError$min is greater than $max. The method does not swap the two values.

Examples

Roll a die

<?nvs
// Shows how to roll a die, and that both ends of the range come up.
bool $sawOne = false;
bool $sawSix = false;
uint $outside = 0;
uint $roll = 0;
while ($roll < 1000) {
int $value = Core\Random::int(1, 6);
if ($value == 1) {
$sawOne = true;
}
if ($value == 6) {
$sawSix = true;
}
if ($value < 1 || $value > 6) {
$outside = $outside + 1;
}
$roll = $roll + 1;
}
// No roll is outside 1 to 6. This prints 0.
echo $outside, "\n";
// In 1000 rolls, both 1 and 6 come up. This prints "yes".
echo $sawOne && $sawSix ? 'yes' : 'no', "\n";
Output
0
yes

Bounds in the wrong order

<?nvs
// Shows what happens when the two bounds are the same, and when they are in the wrong order.
// When both bounds are 5, the result is 5. This prints 5.
echo Core\Random::int(5, 5), "\n";
// A lower bound above the upper bound throws an error. The bounds are not swapped.
try {
echo Core\Random::int(10, 1), "\n";
} catch (Throwable $e) {
echo 'Error: ', $e->message, "\n";
}
Output
5
Error: Core\Random::int(): the range is empty — the lower bound 10 is above the upper bound 1, and both ends are inclusive

A six digit login code

<?nvs
// Shows how to make a six-digit code to send to a user when they log in.
// Any number from 0 to 999999 is allowed. `Core\Str::padStart` adds zeros at the
// front, so 4711 becomes "004711".
int $number = Core\Random::int(0, 999999);
string $code = Core\Str::padStart($number as string, length: 6, padding: '0');
// The code changes on every run, so this prints only what is always true.
echo Core\Str::length($code), "\n";
echo Core\Regex::matches($code, '^[0-9]{6}$') ? 'six digits' : 'not six digits', "\n";
Output
6
six digits