PHP rand() 函式
定義和用法
**rand()** 函式使用偽隨機生成技術返回一個整數。預設範圍為 0 到特定平臺的 getrandmax()。在 64 位 Windows 作業系統中,該值為 2147483647。rand() 函式可以不帶引數(在這種情況下使用預設範圍)或透過指定 min 和 max 引數呼叫。
此函式始終返回一個整數。
語法
rand ( void ) : int rand ( int $min , int $max ) : int
引數
| 流水號 | 引數 & 描述 |
|---|---|
| 1 | min 返回數字的下限。預設值為 0 |
| 2 | max 返回數字的上限。預設值為 getrandmax() |
返回值
PHP rand() 函式使用偽隨機生成技術返回 min 和 max 之間的整數。請注意,不建議將其用於加密目的。
PHP 版本
此函式可用於 PHP 4.x、PHP 5.x 和 PHP 7.x。
示例
此示例未帶引數呼叫 rand() 來返回隨機數 −
<?php echo "random number with no parameters rand() = " . rand() . "
"; echo "another random number with no parameters rand() = " . rand() . "
"; ?>
輸出
它可能會產生以下結果(由於是隨機數,每次返回不同的數字的可能性更高)−
random number with no parameters rand() = 1663374457 another random number with no parameters rand() = 888196648
示例
以下示例為 rand() 函式指定 min 和 max 引數 −
<?php echo "rand(11,30) = " . rand(11,30) . "
"; echo "rand(11,30) = " . rand(11,30) . "
"; ?>
輸出
它將產生以下結果 −
rand(11,30) = 29 rand(11,30) = 22
示例
min 和 max 引數的浮點值的廢棄部分將被忽略 −
<?php echo "rand(10.5,50.95) = " . rand(10.55, 50.95) . "
"; ?>
輸出
它將產生以下結果 −
rand(10.5,50.95) = 45
示例
min 和/或 max 引數的字串值將導致錯誤
<?php
echo "rand("aa", "bb") = " . rand("aa","bb") . "
";;
?>輸出
它將產生以下結果 −
PHP Parse error: syntax error, unexpected 'aa' (T_STRING), expecting ',' or ';'
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP