Virtual Brain Online Logo

Bookmark: Root \ PHP \ How to Generate a Random Number with PHP

How to Generate a Random Number with PHP


Last Updated: 2006-01-18

To generate a random number in php 4.2.0+ you can use

$number = rand();
$number = ran(0,1000);
The first one creates a random number between zero and the max random number value, RAND_MAX.

In earlier PHP versions, the random number generator requires a seed before it can be used. Here is the example provided by php.net
<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$randval = rand();
?>

I have found other people suggesting a google search for "Mersenne Twister" to achieve greater randomness. I have not followed the lead since "somewhat random" is enough for my current applications.

Originally Posted by Skylinux @ 2006-01-17 22:33:04

 

No Comments yet .....

 

Add Your Comment:

Note: All posts require administrator approval. Please allow 24 hours for message approval.

Name:
E-Mail:
Title
Plain text only, less then 65 000 characters.

Please write the following string into the box below: QWERTY

Please answer the question above and type the answer into the text box below.