Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Generates a random integer with a large number of digits.
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;
}
@marianogappa

This comment has been minimized.

Copy link
Owner Author

@marianogappa marianogappa commented Mar 29, 2015

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment