Web студия "GrandView"
  Главная   Написать Контакты
   
   
О проекте
Руководство php
 

rand

(PHP 3, PHP 4, PHP 5)

rand -- Генерирует случайное число

Описание

int rand ( [int min, int max] )

При вызове без параметров min и max, возвращает псевдослучайное целое в диапазоне от 0 до RAND_MAX. Например, если вам нужно случайное число между 5 и 15 (включительно), вызовите rand (5, 15).

Пример 1. Пример

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

echo
rand(5, 15);
?>

Пример выше выведет что-то наподобие этого:

7771
22264
11

Замечание: На некоторых платформах (таких как Windows) RAND_MAX всего лишь 32768. Чтобы расширить диапазон, используйте параметры min и max, или обратитесь к функции mt_rand().

Замечание: Начиная с PHP 4.2.0, больше нет необходимости инициализировать генератор случайных чисел функциями srand() или mt_srand(), поскольку теперь это происходит автоматически.

Замечание: В версиях до 3.0.7 max определяло диапазон генерирования. Например, чтобы получить число от 5 до 15, нужно было вызвать rand (5, 11).

См. также: srand(), getrandmax() и mt_rand().



round> <rad2deg
Last updated: Sat, 27 Jan 2007
 
add a note add a note User Contributed Notes
rand
Ishtar
10-Sep-2007 06:18
A small comment on phpdev-dunnbypauls conclusion that rand() only generates numbers that are a multiply of 3.
<?php
$n
= rand(0,100000); // with MAX_RAND=32768
?>
Since, 100000/32768=3.05 you get multiples of 3. The random integer will be multiplied by 3.05 to fit between 0 and 100000. rand() works fine, if you don't ask for bigger numbers then RAND_MAX.
jfkallen at hotmail dot com
17-Aug-2007 07:21
In regards to mno2go's note below on randomly generated strings, I am not sure what's inefficient about this.  I like it and am using it in several modules (so thanks).  I made a few tweaks though.  There is a fence-post error in the code (a string's range is 0 to n-1).  There is also excessive calls to strlen.

<?php
   
function generateCode($length=6) {
       
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
       
$code = "";
       
$clen = strlen($chars) - 1//a variable with the fixed length of chars correct for the fence post issue
       
while (strlen($code) < $length) {
           
$code .= $chars[mt_rand(0,$clen)];  //mt_rand's range is inclusive - this is why we need 0 to n-1
       
}
        return
$code;
    }
?>
alishahnovin at hotmail dot com
13-Aug-2007 10:39
Quick function that returns an array of unequal random numbers. Works well if you need to assign random values, but want them to all be unique.

<?php
function randiff($min, $max, $num) {
    if (
$min<$max && $max-$min+1 >= $num && $num>0) {
       
$random_nums = array();
       
$i=0;
        while(
$i<$num) {
           
$rand_num = rand($min, $max);
            if (!
in_array($rand_num, $random_nums)) {
               
$random_nums[] = $rand_num;
               
$i++;
            }
        }
        return
$random_nums;
    } else {
        return
false;
    }
}
?>

So rather than:

<?php
$var1
= rand(0,10);
$var2 = rand(0,10);
?>

Which could potentially give you two of the same values, you can use:

<?php
$nums
= randiff(0,10,2);
$var1 = $nums[0];
$var2 = $nums[1];
?>
mno2go at gmail dot com
03-Aug-2007 02:30
Perhaps not the most efficient way, but one that is quite simple and provides for easy control over characters used in the generated strings/passwords:

<?php
   
function generateCode($length=6) {
       
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
       
$code = "";
        while (
strlen($code) < $length) {
           
$code .= $chars[mt_rand(0,strlen($chars))];
        }
        return
$code;
    }
?>
rok dot kralj at gmail dot com
16-Jun-2007 12:43
rand function returns just a whole numbers. If you want a random float, then here's an elegant way:

<?php
function random_float ($min,$max) {
   return (
$min+lcg_value()*(abs($max-$min)));
}
?>
bozo_z_clown at yahoo dot com
23-May-2007 05:36
Note that the automatic seeding seems to be done with the current number of seconds which means you can get the same results for several runs on a fast server.  Either call srand() yourself with a more frequently changing seed or use mt_rand() which doesn't appear to suffer from the problem.
blackened at live dot com
29-Apr-2007 08:24
DKDiveDude forgot one thing in his function.
I tested it, and I found out the random output could even be smaller then $intMin.
This was because he forgot to multiply $intMin with $intPowerTen.
Below DKDiveDude's function with the edit

<?php
// Floating point random number function
// April 2007, Ren
Новости
11 июля 2007
Сайт запущен
© 2007 info@grandviewstudio.com

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 324

Deprecated: Function set_magic_quotes_runtime() is deprecated in /home/sites/grandviewstudiocom/www/65f67d67a94ad980786580ae69e11c07/sape.php on line 330
Z058440144362 Z348613067571