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
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.

Link to comment
Share on other sites

Quite easy. Say you want a random number that must have a length of 5.

 

Given that information, we know that it must be between 10000 and 99999, so:

 

mt_rand(10000, 99999);

 

Done.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.