PHP Tutorial - PHP rand() Function






Definition

The rand() function returns random numbers. If you call it with no parameters, it will return a number between 0 and the value returned by getrandmax().

Syntax

PHP rand() Function has the following syntax.

int rand ( [int min, int max] )

Parameter

ParameterIs RequiredDescription
minOptional.Lowest number to be returned. Default is 0
maxOptional.Highest number to be returned. Default is getrandmax()

If you supply it with two parameters, rand() will use those numbers as the upper and lower limits of the random number, inclusive of those values. That is, if you specify 1 and 3, the value could be 1, 2, or 3.





Return

Item Value
Return ValueA random integer between min (or 0) and max (or getrandmax() inclusive)
Return Type Integer

Note

If you want a random integer between 10 and 100 (inclusive), use rand (10,100). The mt_rand() function produces a better random value, and is 4 times faster than rand().

Example 1


<?PHP
$random = rand(); 
$randrange = rand(1,10); 
?>

The numbers generated by rand() are more predictable than using the mt_rand() function.





Example 2

Display Random picture

<html>
 <body>
 <?php
  srand( microtime() * 1000000 );
  $num = rand( 1, 4 );
  switch( $num ){
    case 1 : $car = "a.jpg"; $url="a.php";      break;
    case 2 : $car = "f.jpg"; $url="f.php";   break;
    case 3 : $car = "j.jpg"; $url = "j.php";  break;
    case 4 : $car = "p.jpg"; $url = "p.php"; break;
  }
  $banner = "<a href='$url'>";
  $banner.= "<img src='$car'";
  $banner.= "width='380' height='110'>";
  $banner.="</a>";
  echo( $banner );
 ?>

 </body>
</html>