Skip to content

Instantly share code, notes, and snippets.

@NewEXE
Last active November 30, 2021 08:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NewEXE/760bc6f92548f784566894c2247a976f to your computer and use it in GitHub Desktop.
Save NewEXE/760bc6f92548f784566894c2247a976f to your computer and use it in GitHub Desktop.
Fast and simple getRandNumber function (PHP)
<?php
$num = getRandNumber(5);
var_dump($num); // 5-digits number like 48149
/**
* Returns fixed-length random integer.
*/
function getRandNumber(int $length): int
{
if($length > 19) {
throw new \RuntimeException('Maximum value for a 64-bit signed integer was overheaded');
}
$min = '1' . str_repeat('0', $length-1);
$max = str_repeat('9', $length);
return rand((int) $min, (int) $max);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment