Posts Tagged ‘random code’


Courtesy:-http://hayageek.com/php-random-number/

In PHP Random Number Generator, I have explained how to Generate a random number with in a range / Generate a random string with given length.In PHP,  we can use rand() function to generate random number. using this function we can make random string also.

PHP rand() Syntax:

1
2
3
4
5
//Generates random number
int rand(void);
//Generate random number in range from $min , to $max (inclusive)
int rand($min,$max);

1).PHP Random Number

1
2
$rand_value =rand();
echo $rand_value."\n";

2).PHP Random Number in a Range(10..100)

1
2
$rand_value = rand(10,100); //generates a number from 10 to 100
echo $rand_value."\n";

3).PHP Generate Random String

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function gen_random_string($length=16)
{
    $chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";//length:36
    $final_rand='';
    for($i=0;$i<$length; $i++)
    {
        $final_rand .= $chars[ rand(0,strlen($chars)-1)];
    }
    return $final_rand;
}
echo gen_random_string()."\n"; //generates a string
echo gen_random_string(8)."\n"; //generates a string with length 8

 

4).PHP Generate random number with given length

1
2
3
4
5
6
7
8
9
10
11
12
13
function gen_random($length=32)
{
    $final_rand='';
    for($i=0;$i< $length;$i++)
    {
        $final_rand .= rand(0,9);
    }
    return $final_rand;
}
echo gen_random(10)."\n";//random number with length 10
echo gen_random()."\n";//random number with length 32
Advertisements