PHP: Generate random number and string

Here are code samples to generate random number and strings in PHP.

Generate random numbers between 1 and 1000


$num = rand(1,1000);

Using mtrand() function for better random number generation


$num = mt_rand(1,1000);

Generate a unique combination of numbers and letters. Works with PHP5 and higher.


$unique = uniqid();

Using md5() and uniqid() function to make the string more complex. md5() function generates 32 character long string. uniqid() works only with PHP5 or higher.


$md5_unique = md5(uniqid());

Generate random string from a given string. Randomly shuffling a given string.


$string = "Mukesh Chapagain";
$randomString = str_shuffle($string);

Generate random number using time() function. The number changes every second. This returns the current unix timestamp.


$time = time();

Hope it helps.
Thanks.