PHP/Math/rand

Материал из Web эксперт
Перейти к: навигация, поиск

Dice Rolling Simulator

 
<?php
function roll_dice($number, $sides, $values = false) {
    $dice = array();
    for ($i = 0; $i < $number; $i++) {
        $dice[] = rand(1, $sides);
    }
    if ($values) {
        return $dice;
    } else {
        return array_sum($dice);
    }
}
$roll_3d6 = roll_dice(3, 6);
echo "<pre>Dice roll = {$roll_3d6}\n";
$rm_stats = roll_dice(10, 100, true);
print_r($rm_stats);
echo "</pre>";
?>



Generate random numbers (integer values) between 0 and MAX_RAND by calling rand() or mt_rand() without any arguments

 
<?php 
echo "rand() = " . rand() . "\n"; 
echo "mt_rand() = " . mt_rand() . "\n"; 
?>



int rand ( [int min, int max] ) returns random numbers

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



Random Images

 
<html>
 <head>
  <title>Random Images</title>
 </head>
 <body bgcolor = "#000000" >
 <?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\" border=\"0\" >";
  $banner.="</a>";
  echo( $banner );
 ?>
 </body>
</html>



Random Numbers

 
<html>
 <head>
  <title>Random Numbers</title>
 </head>
 <body>
 <?php
  srand( microtime() * 1000000 );
  $num = rand( 1, 100 );
  echo( "Microtime:" . microtime() . "<br>");
  echo( "A random number: " . $num . "<br>");
  $num = rand( 1, 100 );
  echo( "Another random number:" . $num );
 ?>
 </body>
</html>