Skip to content

Instantly share code, notes, and snippets.

@marianogappa
Created March 29, 2015 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marianogappa/6170aa5bddcf7437100d to your computer and use it in GitHub Desktop.
Save marianogappa/6170aa5bddcf7437100d to your computer and use it in GitHub Desktop.
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
Copy link
Author

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