faqts : Computers : Programming : Languages : PHP : Function Libraries

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

41 of 43 people (95%) answered Yes
Recently 10 of 10 people (100%) answered Yes

Entry

How can I generate a random number in PHP?

Aug 12th, 1999 22:33
Nathan Wallace, David den Boer, Sander Pilon, Teodor Cimpoesu


The examples below produce a random number between 0 and 5 inclusive. 
That is, the possible values are 0,1,2,3,4,5.

This works for me every time :

      srand((double)microtime()*1000000);
      $randval = rand(0, 5);

If you have an old version of PHP then you might need to use this
instead:

    srand((double)microtime()*10000);
    $t=rand();
    $number = rand()%6;

Alternatively, for a very simple random generator use:

    $number = time() % 6;