rand

(PHP 3, PHP 4, PHP 5)

rand -- 產生一個隨機整數

說明

int rand ( [int min, int max] )

若果沒有提供可選參數 minmaxrand() 返回 0 到 RAND_MAX 之間的偽隨機整數。例如想要 5 到 15(內含 5 和 15)之間的隨機數,用 rand(5, 15)

例子 1. rand() example

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

echo 
rand(515);
?>

上例的輸出類似於:

7771
22264
11

注: 在某些平台下(例如 Windows)RAND_MAX 只有 32768。若果需要的範圍大於 32768,那麼指定 minmax 參數就可以建立大於 RAND_MAX的數了,或是考慮用 mt_rand() 來替代之。

注: 自 PHP 4.2.0 起,不再需要用 srand()mt_srand() 函數給隨機數發生器播種,現已自動完成。

注: 在 3.0.7 之前的版本中,max 的含義是 range。要在這些版本中得到和上例相同 5 到 15 的隨機數,簡短的例子是 rand (5, 11)

參見 srand()getrandmax()mt_rand()