在本文中,我們將學習 PHP 中的隨機數產生器。那什麼是隨機數產生器呢?
我們可以使用內建函數來產生隨機數或整數。這些功能有什麼作用?這些函數在最小值和最大值範圍內產生不同的數字集。每次呼叫此函數時,它都會產生一個唯一的數字。我們可以產生任何編號的數字,例如 2 位數字、3 位數字等。
廣告 該類別中的熱門課程 PHP 開發人員 - 專業化 | 8 門課程系列 | 3次模擬測驗開始您的免費軟體開發課程
網頁開發、程式語言、軟體測試及其他
數字在範圍內洗牌並相應地產生。有各種內建函數可以產生隨機數。
現在我們將學習產生偽隨機數的不同函數:
我們將學習所提到的每種類型函數的語法及其範例。
文法:
雷雷範例:
雷雷輸出:
此函數為 rand() 函數提供範圍。
文法:
雷雷其中 min 是可選的最小值,表示最低數值,max 是可選的最大值,表示最高數值。
此外,min 的預設值為零,max 的預設值是 getrandmax() 函數值。函數的回傳類型始終是整數。
範例:
雷雷輸出:
文法:
雷雷其中 min 是可選值,表示最小數字,max 是可選值,表示最大數字。 min 的預設值為 0,max 的預設值為給定的最高值。傳回類型是整數。
範例:
雷雷輸出:
文法:
雷雷函數傳回一個整數值
範例:
雷雷輸出:
文法:
雷雷此函數傳回一個整數值。
範例:
雷雷輸出:
文法:
雷雷其中種子是可選值,且此函數不傳回任何內容。
範例:
雷雷輸出:
Example:
'; mt_srand(5); echo mt_rand(1,5); ?>
Output:
In the following example we have used rand(),rand(min,max) and mt_rand().
Code:
Any random number ---->'. rand(); echo '
Any random number ---->'. rand(); echo '
'; // random number with range echo 'Following are the different random values within a range '; echo '
Any random number within the range from 0 to 9----> '. rand(0,9); echo '
Any random number within the range from 1000 to 9999 ---->'. rand(1000,9999); echo '
'; // random number with range echo 'Following are the different random values using mt_rand() '; echo '
Using mt_rand()---->'. mt_rand(1000,9999); echo '
Using mt_rand()---->'. mt_rand(100,999); ?>
Output:
Floating-point numbers represent a number with decimals that are of the type float. Examples – 10.0, 8.12, 6.23e-5, 2.345, 2.98e+10 and more.
Code:
'; echo "
".fun(1, 10, 2); ?>
Output:
In this article, we learned about various functions used to generate a random number in PHP. These functions are explained with sample examples. Hope this article is found useful to anyone who wants to learn a random number generator in PHP.
以上是PHP 中的隨機數產生器的詳細內容。更多資訊請關注PHP中文網其他相關文章!