Created
March 29, 2015 06:03
-
-
Save marianogappa/6170aa5bddcf7437100d to your computer and use it in GitHub Desktop.
Generates a random integer with a large number of digits.
This file contains hidden or 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
function big_rand_integer($digits) { | |
if(!is_numeric($digits) || $digits <= 0) | |
return '0'; | |
if(!is_integer($digits)) | |
$digits = (int)ceil($digits); | |
$multiplier = (int)ceil($digits / 9.0); | |
$function = function() { | |
return(str_pad(strrev((string)mt_rand()), 9, '0', STR_PAD_LEFT)); | |
}; | |
return substr(str_repeat_func($function, $multiplier), 0, $digits); | |
} | |
function str_repeat_func($function, $multiplier) { | |
if(!is_callable($function) || !is_integer($multiplier) || $multiplier <= 0) | |
return ""; | |
$accumulator = ""; | |
for($i = 0; $i < $multiplier; $i++) | |
$accumulator .= call_user_func($function); | |
return $accumulator; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Returns a string with the number. Useful only when $digits > 9. On extraneous input, it'll return '0'. If you give it a decimal, it'll round it up to the next integer. It uses the mt_rand function internally. It attempts to save cycles by using the 9 useful digits of mt_rand(mt_get_max_rand) instead of calling it once per digit.