Skip to content

Instantly share code, notes, and snippets.

@jgv
Created August 19, 2010 16:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jgv/538323 to your computer and use it in GitHub Desktop.
Save jgv/538323 to your computer and use it in GitHub Desktop.
generate random numbers in php with no repeats
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
@saiedlakhdar
Copy link

i got error undefined $digits variable ^^

@abarghaz
Copy link

abarghaz commented Mar 15, 2018

Hi

you should to give a value to variable before loop

Like this :

function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
$digits = "";
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}

@nanadjei
Copy link

Getting the same error.

@arif98741
Copy link

arif98741 commented Jun 14, 2018

Problem solved

$digits = '';
function randomDigits($length){
    $numbers = range(0,9);
    shuffle($numbers);
    for($i = 0; $i < $length; $i++){
    	global $digits;
       	$digits .= $numbers[$i];
    }
    return $digits;
}

`

@iconmedia
Copy link

How can i authenticated this against database values?

@trelljaret
Copy link

BS

@sodmond
Copy link

sodmond commented Aug 26, 2020

How can i authenticated this against database values?

You can just search the value in your database, if it returns null then it has not been stored yet.

@medbend
Copy link

medbend commented Jan 11, 2022

just doing like that
function randomDigits($length){ // function with parameter you must define it before callback the function
global $digits; // global to access from anyway
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
echo randomDigits(4); // 4 mean your number between 4 digits

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