Jump to content

Fixed Length Random Number


livethedead

Recommended Posts

This isn't for anything practical, I'm just fiddling. Anyways, I'm wondering if there's anyway to make this more efficient since at higher lengths it could become really heavy. $l is length of the number.

 

	function fixed_random($l) {
	$number = "";
	do {
		$r = mt_rand(0, $l);
		$number .= $r;
	} while (strlen($number) < $l);
return $number;
}

Link to comment
https://forums.phpfreaks.com/topic/262252-fixed-length-random-number/
Share on other sites

<?php
function fixed_random($digits) {
    $range_start = pow(10, $digits-1); // $digits=1, $range_start=0, 2:10, 3:100 ....
    $range_end = pow(10, $digits)-1; // $digits=1, $range_end=9, 2:99, 3: 999 ....
    $number = mt_rand($range_start, $range_end);
    return $number;
?>

 

Not tested, just my first thought.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.