Last active
November 30, 2021 08:21
-
-
Save NewEXE/760bc6f92548f784566894c2247a976f to your computer and use it in GitHub Desktop.
Fast and simple getRandNumber function (PHP)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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