PHP rand() Function

In this chapter you will learn:

  1. Definition for PHP rand() Function
  2. Syntax for PHP rand() Function
  3. Parameter for PHP rand() Function
  4. Return for PHP rand() Function
  5. Note for PHP rand() Function
  6. Example - Generate Random number
  7. Example - Display Random picture

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>//j a v a 2  s. com
 <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>

Next chapter...

What you will learn in the next chapter:

  1. Definition for PHP round() Function
  2. Syntax for PHP round() Function
  3. Parameter for PHP round() Function
  4. Return for PHP round() Function
  5. Note for PHP round() Function
  6. Example - round value in PHP
  7. Example - Round value and set number of decimal places to keep
  8. Example - Round float with round mode