How to generate a random number in PHP

5 views
Skip to first unread message

Abdul Haseeb

unread,
Sep 18, 2008, 3:03:37 PM9/18/08
to PHP Hacks
Hi ! i am new to php. so , i wanted to know how can i generate a
random alphanumeric number in php.
regards
haseeb

Alex Weber

unread,
Sep 27, 2008, 5:40:04 PM9/27/08
to PHP Hacks
this a function i use to generate random passwords, feel free to use
it:

function newPassword($length) {
$password = '';
$possible = '123456789abcdefghjkmnpqrtuvwxyz123456789';
$i = 0;
while ($i < $length) {
$char = substr($possible, mt_rand(0, strlen($possible)-1), 1);
if (!strstr($password, $char)) {
$password .= $char;
$i++;
}
}
return $password;
}

if you wanted to generate random alphanumeric numbers without
specifying a string of possible combinations you could always use:

chr() - http://www.php.net/chr
rand() - http://www.php.net/rand
and an ASCII table - http://www.asciitable.com/

so you'd be set up like this:

1) use a loop to control the length (like above)
2) generate a random number between the ASCII intervals you want (see
the ASCII Table) using rand()
3) convert the number to an ASCII character using char() and
concatenate it to your random number variable

-Alex

Chandu Gandhi

unread,
Oct 1, 2008, 2:00:01 AM10/1/08
to PHP Hacks
Hi i m chandu gandhi I have 3 year experience in PHP
you can create random alphanumeric number by this function

-> rand(min,max)

cecilomar

unread,
Oct 12, 2008, 10:16:40 AM10/12/08
to PHP Hacks
I think AleBut that gives you a mere number, not an alphanumerical
string.

Alex Weber

unread,
Oct 15, 2008, 7:02:27 AM10/15/08
to PHP Hacks
Actually rand() generates random INTEGERS

an "alphanumeric number" consists of both letters and numbers...

so rand() is fine for generating only numbers, but not alphanumeric
numbers!

Abdul Haseeb

unread,
Nov 9, 2008, 12:32:57 PM11/9/08
to PHP Hacks
thanks to everybody. You were all of great help.
> > > haseeb- Hide quoted text -
>
> - Show quoted text -
Reply all
Reply to author
Forward
0 new messages