Home » PHP

Random number, string generation in PHP

5 March 2008 745 views Popularity: 2% Share/Bookmark

email

Explaining/Illustrating different ways to generate random numbers and strings in PHP


<?php
/*********************************

<span id="more-43"></span>

RANDOM STRING GENERATION

Explaining/Illustrating different ways to generate random numbers and strings

Programmed By: Mukesh Chapagain

http://www.chapagain.com.np

http://blog.chapagain.com.np

*********************************/

//generating random numbers

//generating random numbers between 1 and 1000
$num = rand(1,1000);
echo "Random number from rand function: ";
echo $num;
echo "<br/><br/>";

//we can use mtrand() function for better random number generation
$mt_num = mt_rand(1,1000);
echo "Random number from mt_rand function: ";
echo $mt_num;
echo "<br/><br/>";

//generating a unique combination of numbers and letters
//works with PHP5 or higher
$unique = uniqid();
echo "Random string from uniqid function: ";
echo $unique;
echo "<br/><br/>";

//making the string more complex generated by uniqid function
//by using md5() function
//md5 function generates 32 character long string
//the function uniqid() works only with PHP5 or higher
$md5_unique = md5(uniqid());
echo "Random string from md5 to uniqid function: ";
echo $md5_unique;
echo "<br/><br/>";

//generating random string from a given string
//randomly shuffling a given string
$string = "Mukesh Chapagain";
$rand_string = str_shuffle($string);
echo "Random string from str_shuffle function: ";
echo $rand_string;
echo "<br/><br/>";

//generating random number from time() function
//the number changes every second
//this returns the current unix timestamp
$time = time();
echo "Random number from time function: ";
echo $time;
echo "<br/><br/>";

?>

Related posts:

  1. PHP: Generating Multiple Random String
  2. Generating random image
  3. PHP: How to get integer or decimal from a string?
  4. PHP: Parse Unparse String Array
  5. Magento: Set Random Order in Collection using RAND()
  6. PHP: Simple and easy way to format URL string
  7. jQuery: How to replace string, div content and image src?
  8. PHP : Read Write Xml with SimpleXML
  9. Javascript: How to get current URL without Query string?
  10. Convert string to datetime and datetime to string in C#
  • http://roshanbh.com.np Roshan Bhattarai

    you might know that no random no is 100% pure random no as it depends upon particular factor for generating the random values. It’s better to seed the random no generator before generating the random number. I better prefer the approach given in the following link.
    http://www.php.net/srand

  • http://www.chapagain.com.np Mukesh

    Thanks. But I was not illustrating the best random no. generation method. I was just showing different approaches to do this thing.