Php как вывести случайное число

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

(PHP 4, PHP 5, PHP 7)

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

Описание

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

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

Список параметров

Наименьшее значение, которое может быть возвращено (по умолчанию: 0)

Наибольшее значение, которое может быть возвращено (по умолчанию: getrandmax() )

Возвращаемые значения

Псевдослучайное значение в диапазоне от min (или 0) до max (или getrandmax() ).

Примеры

Пример #1 Пример использования rand()

echo rand () . «\n» ;
echo rand () . «\n» ;

echo rand ( 5 , 15 );
?>

Результатом выполнения данного примера будет что-то подобное:

Примечания

Данная функция не генерирует криптографически безопасные значения и не должна использоваться в криптографических целях. Если вам требуется криптографически безопасное значение, подумайте об использовании функции openssl_random_pseudo_bytes() вместо данной.

Смотрите также

  • srand() — Изменяет начальное число генератора псевдослучайных чисел
  • getrandmax() — Возвращает максимально возможное случайное число
  • mt_rand() — Генерирует случайное значение методом mt
  • openssl_random_pseudo_bytes() — Generate a pseudo-random string of bytes

Источник

random_int

random_int — Генерирует криптографически безопасные псевдослучайные целые числа

Описание

Генерирует криптографически случайные целые числа, пригодные для использования в криптографических целях, где случайность результата критична, например, для перемешивания колоды карт для игры в покер.

Источник случайных величин, используемых данной функцией:

  • В Windows всегда используется » CryptGenRandom() Начиная с PHP 7.2.0, вместо него всегда будет использоваться » CNG-API.
  • В Linux, если доступен, используется системный вызов » getrandom(2).
  • На других платформах используется /dev/urandom .
  • Если доступные источники случайных величин отсутствуют, то выбрасывается исключение Exception .

Замечание: Эта функция была добавлена в PHP 7.0, а для версий с 5.2 по 5.6 включительно доступна » пользовательская реализация.

Список параметров

Нижняя граница диапазона, из которого будет выбрано случайное число. Должна быть больше или равна PHP_INT_MIN .

Верхняя граница диапазона, из которого будет выбрано случайное число. Должна быть меньше или равна PHP_INT_MAX .

Возвращаемые значения

Генерирует криптографически безопасное случайное целое число в диапазоне от min до max , включительно.

Ошибки

  • Если подходящие источники случайных величин отсутствуют, то выбрасывается исключение Exception .
  • Если задан некорректный параметр, то выбрасывается исключение TypeError .
  • Если задать max меньше чем min , то будет выброшено исключение класса Error .

Примеры

Пример #1 Пример random_int()

Результатом выполнения данного примера будет что-то подобное:

Источник

array_rand

(PHP 4, PHP 5, PHP 7, PHP 8)

array_rand — Выбирает один или несколько случайных ключей из массива

Описание

Выбирает одно или несколько случайных значений из массива. Возвращает ключ (или ключи) данных случайных элементов. Данная функция использует псевдослучайный генератор и не предназначена для использования в криптографических целях.

Список параметров

Определяет количество выбираемых элементов.

Возвращаемые значения

Если вы выбираете только одно значение, функция array_rand() возвращает ключ, соответствующий этому значению. В обратном случае, она возвращает массив ключей, соответствующих случайным значениям. Это сделано для того, чтобы дать возможность выбрать из массива как случайные значения, так и случайные ключи. Если возвращается несколько ключей, они будут возвращены в том порядке, в котором они присутствовали в исходном массиве. Попытка выбрать больше элементов, чем есть в массиве, сгенерирует ошибку уровня E_WARNING и вернёт NULL.

Список изменений

Версия Описание
7.1.0 Внутренний алгоритм получения случайных чисел изменён с функции rand библиотеки libc на генератор на базе » Вихря Мерсенна.

Примеры

Пример #1 Пример использования array_rand()

Смотрите также

User Contributed Notes 5 notes

If the array elements are unique, and are all integers or strings, here is a simple way to pick $n random *values* (not keys) from an array $array:

( array_flip ( $array ), $n ); ?>

/**
* Wraps array_rand call with additional checks
*
* TLDR; not so radom as you’d wish.
*
* NOTICE: the closer you get to the input arrays length, for the n parameter, the output gets less random.
* e.g.: array_random($a, count($a)) == $a will yield true
* This, most certainly, has to do with the method used for making the array random (see other comments).
*
* @throws OutOfBoundsException – if n less than one or exceeds size of input array
*
* @param array $array – array to randomize
* @param int $n – how many elements to return
* @return array
*/
function array_random (array $array , int $n = 1 ): array
<
if ( $n 1 || $n > count ( $array )) <
throw new OutOfBoundsException ();
>

return ( $n !== 1 )
? array_values ( array_intersect_key ( $array , array_flip ( array_rand ( $array , $n ))))
: array( $array [ array_rand ( $array )]);
>

// An example how to fetch multiple values from array_rand
$a = [ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’ , ‘g’ ];
$n = 3 ;

// If you want to fetch multiple values you can try this:
print_r ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) );

// If you want to re-index keys wrap the call in ‘array_values’:
print_r ( array_values ( array_intersect_key ( $a , array_flip ( array_rand ( $a , $n ) ) ) ) );

array_rand () takes a random value without ever being able to go back in its choice of random value.
A simple example:
I decide to mix an array of 10 entries to retrieve 3 values. This choice will give increasing and random values.

$pm = array_rand($myarray,3);
// $pm return array(0->0,1->6,2->8)

But if I decide to shuffle an array of 10 entries to get 10 entries, array_rand () will choose to assign a value to each return value and therefore the return array will not be random.

$gm = array_rand($myarray,count($myarray));
// $gm not random array(0->0,1->1,2->2,3->3,4->4,5->5,6->6,7->7,8->8,9->9)

The easiest way to have a truly random value:
either use array_rand () in a loop of 1 value at a time

$deg = range(-60,60);
$size = range(16,64);
$color = [«blue»,»red»,»green»,»pink»,»orange»,»purple»,»grey»,»darkgreen»,»darkkhaki»];
$i = 0;
$longueur = 10;
do <
++$i;
printf(» %s «,
$deg[array_rand($deg)],
$size[array_rand($size)],
$color[array_rand($color)],
$alnum[array_rand($alnum)]);

Источник

Php как вывести случайное число

(PHP 4, PHP 5, PHP 7, PHP 8)

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

Описание

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

Данная функция не генерирует криптографически безопасные значения и не должна использоваться в криптографических целях. Если вам требуется криптографически безопасное значение, подумайте об использовании функций random_int() , random_bytes() или openssl_random_pseudo_bytes() вместо данной.

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

Замечание: Начиная с PHP 7.1.0, rand() использует тот же алгоритм получения случайных чисел, что и mt_rand() . Для сохранения обратной совместимости, функция rand() позволяет задавать параметр max меньше, чем параметр min . Функция mt_rand() в такой ситуации будет возвращать false

Список параметров

Наименьшее значение, которое может быть возвращено (по умолчанию: 0)

Наибольшее значение, которое может быть возвращено (по умолчанию: getrandmax() )

Возвращаемые значения

Псевдослучайное значение в диапазоне от min (или 0) до max (или getrandmax() ).

Список изменений

Примеры

Пример #1 Пример использования rand()

echo rand () . «\n» ;
echo rand () . «\n» ;

echo rand ( 5 , 15 );
?>

Результатом выполнения данного примера будет что-то подобное:

Примечания

Диапазон min — max не должен выходить за границы getrandmax() . То есть ( max — min ) getrandmax() . В противном случае, rand() может возвращать менее качественные случайные числа.

Смотрите также

  • srand() — Изменяет начальное число генератора псевдослучайных чисел
  • getrandmax() — Возвращает максимально возможное случайное число
  • mt_rand() — Генерирует случайное значение методом с помощью генератора простых чисел на базе Вихря Мерсенна
  • random_int() — Генерирует криптографически безопасные псевдослучайные целые числа
  • random_bytes() — Генерирует криптографически безопасные псевдослучайные байты
  • openssl_random_pseudo_bytes() — Генерирует псевдослучайную последовательность байт

User Contributed Notes 39 notes

quick way to generate randomish numbers and simple strings.
no messing around with functions, so you can just pop the line into the middle of your existing code.

not the most perfect for sure, but ok for plenty of situations.

= intval ( «0» . rand ( 1 , 9 ) . rand ( 0 , 9 ) . rand ( 0 , 9 ) . rand ( 0 , 9 ) . rand ( 0 , 9 ) ); // random(ish) 5 digit int

$random_string = chr ( rand ( 65 , 90 )) . chr ( rand ( 65 , 90 )) . chr ( rand ( 65 , 90 )) . chr ( rand ( 65 , 90 )) . chr ( rand ( 65 , 90 )); // random(ish) 5 character string

?>

hope someone finds it useful for somthing.

I also enjoy making one-liners.

Here’s a non-regular expression approach. It generates a random 32 character string consisting of, by default, only A-Z, a-z, and 0-9, but you can change the value of $a for other characters. The random string will be in variable $s after this line.

for ( $s = » , $i = 0 , $z = strlen ( $a = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789’ )- 1 ; $i != 32 ; $x = rand ( 0 , $z ), $s .= $a < $x >, $i ++);
?>

If you don’t want the same character to appear beside itself, use this:

for ( $i = 0 , $z = strlen ( $a = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890’ )- 1 , $s = $a < rand ( 0 , $z )>, $i = 1 ; $i != 32 ; $x = rand ( 0 , $z ), $s .= $a < $x >, $s = ( $s < $i >== $s < $i - 1 >? substr ( $s , 0 ,- 1 ) : $s ), $i = strlen ( $s ));
?>

For those of you who want both as a function, use this:

function rand_chars ( $c , $l , $u = FALSE ) <
if (! $u ) for ( $s = » , $i = 0 , $z = strlen ( $c )- 1 ; $i $l ; $x = rand ( 0 , $z ), $s .= $c < $x >, $i ++);
else for ( $i = 0 , $z = strlen ( $c )- 1 , $s = $c < rand ( 0 , $z )>, $i = 1 ; $i != $l ; $x = rand ( 0 , $z ), $s .= $c < $x >, $s = ( $s < $i >== $s < $i - 1 >? substr ( $s , 0 ,- 1 ) : $s ), $i = strlen ( $s ));
return $s ;
>
?>

string $c is the string of characters to use.
integer $l is how long you want the string to be.
boolean $u is whether or not a character can appear beside itself.

Examples:
rand_chars(«ABCEDFG», 10) == GABGFFGCDA
rand_chars(«ABCEDFG», 10, TRUE) == CBGFAEDFEC

Don’t forget, it’s faster to use bitwise operations when you need a random number that’s less than some power of two. For example,

()& 1 ;
// instead of
rand ( 0 , 1 );
// for generating 0 or 1,

rand ()& 3 ;
// instead of
rand ( 0 , 3 );
// for generating 0, 1, 2, or 3,

rand ()& 7 ;
// instead of
rand ( 0 , 7 )
// for generating 0, 1, 2, 3, 4, 5, 6, or 7,
?>

and so on. All you’re doing there is generating a default random number (so PHP doesn’t have to parse any arguments) and chopping off the piece that’s useful to you (using a bitwise operation which is faster than even basic math).

Since many people (myself included) come to this page looking for a way to do a random string, I present a way that uses arrays and shuffle() instead of rand(). This also has the effect of not repeating any characters in the value set.

$arr = str_split(‘ABCDEFGHIJKLMNOP’); // get all the characters into an array
shuffle($arr); // randomize the array
$arr = array_slice($arr, 0, 6); // get the first six (random) characters out
$str = implode(», $arr); // smush them back into a string

Random integers with normal distribution,
it’s not scientifically approved, but worked for me.

/*
* @param float $mean, desired average
* @param number $sd, number of items in array
* @param number $min, minimum desired random number
* @param number $max, maximum desired random number
* @return array
*/
function array_distribute ( $mean , $sd , $min , $max ) <
$result = array();
$total_mean = intval ( $mean * $sd );
while( $sd > 1 ) <
$allowed_max = $total_mean — $sd — $min ;
$allowed_min = intval ( $total_mean / $sd );
$random = mt_rand ( max ( $min , $allowed_min ), min ( $max , $allowed_max ));
$result []= $random ;
$sd —;
$total_mean -= $random ;
>
$result [] = $total_mean ;
return $result ;
>
?>

I agree with Sebmil (http://php.net/manual/en/function.array-rand.php#105265) that «array_rand()» produces weird and very uneven random distribution (as of my local PHP 5.3.8 and my public host’s PHP 5.2.17).
Unfortunately, I haven’t got any access either to a server with the latest PHP version. My info is for those of you who like to check things for themselves and who don’t believe all of the official statements in the docs.
I’ve made a simple adjustment of his test code like this:
= 1 ; // Start value
$c = 50 ; // Count / End value
$test = array_fill ( $s , $c , 0 );
$ts = microtime ( true );
for( $i = 0 ; $i 5000000 ; $i ++) <
$idx = mt_rand ( $s , $c ); // Try it with rand() — simpler but more evenly distributed than mt_rand()
$test [ $idx ]++;
>
$te = microtime ( true );
$te =( $te — $ts )* 1000.0 ; // Loop time in miliseconds

asort ( $test );
echo «Test mt_rand() in » . $te . » ms:
\n» ;
foreach( $test as $k => $v ) echo » $k :\t $v
\n» ;
?>

And it appears to me that simple «$idx=rand(0, count($test)-1);» is much better than «$idx=array_rand($test, 1);».
And what’s more the simpler and a bit slower (0 ms up to total 712.357 ms at 5 mln cycles) «rand()» is better than «mt_rand()» in simple everyday use cases because it is more evenly distributed (difference least vs. most often numbers: ca. 0.20-1.28 % for «rand()» vs. ca. 1.43-1.68 % for «mt_rand()»).
Try it for yourself. although it depends on your software and hardware configuration, range of numbers to choose from (due to random patterns), number of cycles in the loop, and temporary (public) server load as well.

If you are looking for generate a random expression, like password with alphanumeric or any other character, use this function:

function GeraHash ( $qtd ) <
//Under the string $Caracteres you write all the characters you want to be used to randomly generate the code.
$Caracteres = ‘ABCDEFGHIJKLMOPQRSTUVXWYZ0123456789’ ;
$QuantidadeCaracteres = strlen ( $Caracteres );
$QuantidadeCaracteres —;

$Hash = NULL ;
for( $x = 1 ; $x $qtd ; $x ++) <
$Posicao = rand ( 0 , $QuantidadeCaracteres );
$Hash .= substr ( $Caracteres , $Posicao , 1 );
>

//Here you specify how many characters the returning string must have
echo GeraHash ( 30 );
?>

isn’t this just a simpler way of making a random id for somthing? I mean i know that there is a very slight chance that a duplicate could be made but its a very, very, very small chance, nearly impossible.

$rand = mt_rand(0, 32);
$code = md5($rand . time());
echo «$code»;

and if you don’t want it the md5 can be removed, I’ve just added it as a prefer it there 🙂

I have made this example to generate random number with specific length (10).

srand(9);x
function gen () <
$len = 10 ;
$x = » ;
for ( $i = 0 ; $i $len ; $i ++)
<
$x .= intval ( rand ( 0 , 9 ));
>
return $x ;
>

for ( $i = 0 ; $i 100 ; $i ++) <
$x = gen ();
echo $x , PHP_EOL ;

Here’s an interesting note about the inferiority of the rand() function. Try, for example, the following code.

= array( 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 );
for ( $i = 0 ; $i 1000000 ; $i ++) <
$n = rand ( 0 , 100000 );
if ( $n 10 ) <
$r [ $n ]++;
>
>
print_r ( $r );
?>

which produces something similar to the following output (on my windows box, where RAND_MAX is 32768):

Within this range only multiples of 3 are being selected. Also note that values that are filled are always 30 or 31 (no other values! really!)

Now replace rand() with mt_rand() and see the difference.

Much more randomly distributed!

Conclusion: mt_rand() is not just faster, it is a far superior algorithm.

The Windows rand() function is quite a lot worse than merely having a low maximum value. It’s an ordinary Linear Congruential Generator, which means you only need three consecutive values to be able to predict its entire future output.

Given the numbers 13050, 4267, 25352, construct the equations
4267 = (13050a+c) % 32768
25352 = (4267a+c) % 32768

Solving for a and c gives

a = 20077
c = 12345

Which means the next number that should be spat out is (25352×20077+12345) % 32768 = 19105 — which indeed it is.

It’s not the small rand_max that breaks the algorithm, it’s a weakness in the LCG algorithm itself. It’s designed for when you only want a few kinda-random numbers occasionally, not if you want to generate any random-looking data.

Here’s a simple function to generate a random date between a start date and an end date.

It is inclusive of BOTH dates — so using dates 2009-04-01 and 2009-04-03 would generate a random date that could be 2009-04-01, 2009-04-02 or 2009-04-03.

It won’t work if the end date is prior to the start date and if you use a non-existant date (eg 2009-02-30) it defaults to 1970-01-01

the longer version:
function makeRandomDateInclusive ( $startDate , $endDate ) <
$days = round (( strtotime ( $endDate ) — strtotime ( $startDate )) / ( 60 * 60 * 24 ));
$n = rand ( 0 , $days );
return date ( «Y-m-d» , strtotime ( » $startDate + $n days» ));
>
?>

and the one-line version for compactness freaks:
function makeRandomDateInclusive ( $startDate , $endDate ) <
return date ( «Y-m-d» , strtotime ( » $startDate + » . rand ( 0 , round (( strtotime ( $endDate ) — strtotime ( $startDate )) / ( 60 * 60 * 24 ))). » days» ));
>
?>

it is called like this
echo makeRandomDateInclusive ( ‘2009-04-01’ , ‘2009-04-03’ );
?>
Hope this is of some use to someone

Note that the algorithm change in version 7.1.0 broke the repeatability of a random sequence initialized with a given value. For example if you have a program like:

( $argv [ 1 ]);
for ( $i = 0 ; $i 10 ; $i ++) <
echo rand (). PHP_EOL ;
>
?>

It will will no longer produce the same results after version 7.1.0. This can be very important for some kinds of simulations. Hopefully you were using mt_rand() or something better all along, otherwise you will have some digging to do if you want your program to be able to repeat simulations from the pre-7.1.0 days. You will need to look in the PHP source archives to discover the algorithm they used to use and replicate it in your program.

Improved random string generation function:

// Generate a random character string
function rand_str ( $length = 32 , $chars = ‘ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890’ )
<
// Length of character list
$chars_length = ( strlen ( $chars ) — 1 );

// Generate random string
for ( $i = 1 ; $i $length ; $i = strlen ( $string ))
<
// Grab a random character from our list
$r = $chars < rand ( 0 , $chars_length )>;

// Make sure the same two characters don’t appear next to each other
if ( $r != $string < $i - 1 >) $string .= $r ;
>

// Return the string
return $string ;
>
?>

As an further optimization on janoserki[at]gmail[dot]com previous post i would recommend that you optimize you first part of php/sql code to something like this.

// estimate the number of rows in a table
$lekerdezes = mysql_query ( «select count(*) as rows from table» );
while ( $row = mysql_fetch_assoc ( $lekerdezes ))
<
$max = $row [ «rows» ];
>
?>
the count(*) is much faster for the database than grabbing the hole dataset from the table.

Easy way for mysql: random row
the original form is: «. order by rand()»
but this is not the best way, because it’s very slow by a big database (it can take more minutes to complete the request!)
My suggestion:

// estimate the number of rows in a table
$lekerdezes = mysql_query ( «select * from table» );
$max = mysql_num_rows ( $lekerdezes );

// pick one
$rand = rand ( 1 , $max );

$lekerdezes2 = mysql_query ( «select * from table limit $rand , 1» );

Источник

Читайте также:  Чем отмыть бензин с багажника
Оцените статью