When programming PHP you may find the need to use random numbers. You may see this in use on websites that provide changing log-in messages, or random quotes. The random function can be very powerful but is in fact, simple to use.
There are two random functions in php:
int rand ( [int min, int max] )
int mt_rand ( [int min, int max] )

The first function, rand(), returns a pseudo-random integer between min and max.
If you wanted to return a number between say, 5 and 10, you would write
echo rand(5, 10);
If you wanted to return a number between 0 and 10, you would write
echo rand(0, 10);
Finally, using rand on its own will return a random number
echo rand(); //When tested returned: 18639
The second function, mt_rand (Mersenne Twister) takes the same arguments but is far more complex, and will return numbers which appear more random than those returned by rand. That said, even though the numbers appear more random, the execution time is much faster than rand (upto four times faster).
echo mt_rand(5, 10); //7
echo mt_rand(0, 10); //3
echo mt_rand(); //177136487
Ok, so the random functions in PHP are pretty straight forward. But to demonstrate a use of rand i have provided the following code...
switch(rand(1,5))
{
case 1:
$welcomeMessage = 'Welcome to my site'; break;
case 2:
$welcomeMessage = 'Thank you for visiting'; break;
case 3:
$welcomeMessage = 'Hello Visitor'; break;
case 4:
$welcomeMessage = 'Please leave your comments'; break;
case 5:
$welcomeMessage = 'Ah! Welcome my good friend'; break;
}

print $welcomeMessage;
Goodluck

Posted by OLLIE at 14:32pm

No comments yet. Be the first to add one!


Leave a Reply