Php random number from 1 to 10. What's new in PHP7.1: random number generation. Random Numbers in JavaScript

I’ve already been asked a couple of times how I make random quotes on my website in the “Smart Quotes” block. Next, I managed to find out that the problem here is with people not understanding how to output a random element from an array in PHP. The task is simple, but nevertheless, since questions arise, they must be answered.

I'll give you the code right away. Let's say there is an array with a set of quotes. And you need to select one random one of them and output:

The key point is getting a random number. All you have to do is set the right boundaries. If you need to select a random element over the entire length of the array, then it is from 0 to (array length minus 1). And then simply pull out an element from the array with the resulting random index.

As for the task with quotes, it is better to store them in a database. In principle, if the site is very simple, then it can be done in a text file. But if in a database, then it is better to use RAND() and LIMIT in the SQL query so that you immediately get a single and random quote from the database.

To generate a random number, you can use the PHP rand() or mt_rand() function. The requirement to use random numbers often arises in practice for naming variables, files, creating key information, and ensuring security.

Randomness and uniqueness

The PHP random function comes in two variants: rand() and mt_rand(). It is believed that the algorithm in the first case is simpler and generates pseudorandom numbers. The second option has a faster algorithm and well-known mathematical characteristics. In most cases when you need to get a random number, you can use a series of PHP random calls and get a unique combination of numbers.

If you take numbers from 1 to 26 or from 1 to 32 as a basis and get them randomly, you can form key information as a sequence of Latin or Cyrillic letters. In this case, PHP random is a way of generating a sequence of alphabetic information, for example for the purposes of testing communication channels or algorithms.

A random number is rarely unique because it can appear multiple times according to the distribution law of a random variable. But if you combine, in particular, the static variable PHP & Math.random of the JavaScript language, you can get a real unique random number that will not be repeated over time.

Using the Time Function

The time function, both PHP and JavaScript, allows you to form unique combinations of numbers, rarely when a sufficiently large number of events can occur at one point in time and the random variable will be repeated.

By applying PHP random in the range of seconds or milliseconds over a large range of possible values, it is possible to obtain unique random combinations of numbers or letters. What else?

By combining the value of the time function, a sequentially growing number and PHP random, you can ensure reliable security of client and server communication channels, create unique codes for variables, and generate unpredictable events in algorithms.

A PHP random number generator is an excellent solution for most tasks, especially when you need to quickly get high-quality results with minimal effort. Using the rand() and mt_rand functions in conjunction with sequentially growing series of numbers or time values ​​allows you to obtain random numbers, both repeating in values ​​and unique.

Initializes the random number generator. Syntax:

Void srand(int seed)

Initializes the random number generator with the seed value.

Srand((double) microtime()*1000000);
$random = rand();
echo $random;

GETRANDMAX

Returns the largest possible random number. Syntax:

Int getrandmax()

This function returns the maximum value that can be obtained using the rand() random number generation function.

Usually it is 32767

Generates a random number. Syntax:

Int rand()

When called with the optional min and max parameters, this function generates a random number up to and including those parameters. If the min and max parameters are missing, a number ranging from 0 to RAND_MAX is returned.

For this function to work correctly, before using it, you need to initialize the random number generator with the srand() function.

lcg_value()

LCG pseudo-random number generator (PHP 4, PHP 5)

Description:

Float lcg_value (void)

lcg_value() returns a pseudorandom number in the range (0, 1). The function combines two generators with 2^31 - 85 and 2^31 - 249 in a period.

mt_getrandmax()

Shows the largest possible random value (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

Int mt_getrandmax (void)

Shows the maximum value that can be returned by mt_rand()

mt_rand()

Generates the best random value (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

int mt_rand()

Many older versions of random number generators have questionable characteristics and are slow. By default, PHP uses the rand() function to generate random numbers. The mt_rand() function is a good replacement. It uses a random number generator that is 4 times faster than rand() and uses Mersenne Twister.

Called without the optional min and max arguments, mt_rand() returns a pseudo-random value ranging between 0 and RAND_MAX. If you need to get, for example, random values ​​between 5 and 15 inclusive, look for mt_rand (5, 15).

Example of using mt_rand()

The result of running this example will be something like this:

1604716014
1478613278
6

Comment

Note: In versions prior to 3.0.7, the second parameter of the function specified the range of numbers. For example, to obtain random numbers between 5 and 15 in these versions you need to specify the mt_rand(5, 11) function.

mt_srand()

Sets the initial value of the best random number generator (PHP 3 >= 3.0.6, PHP 4, PHP 5)

Description:

Void mt_srand()

Sets the initial value of the random number generator using seed. As of PHP 4.2.0, seed is optional and the default settings for random values ​​are omitted.

Example of using mt_srand()

Note: As of PHP 4.2.0, it is no longer necessary to initialize the random number generator with srand() or mt_srand(), since this is now done automatically.

Technically, the term "random number generator" is nonsense, since numbers themselves are not random. For example, is 100 a random number? What about 25? What this term actually means is that it creates a sequence of numbers that appear randomly. This raises a more difficult question: what is a sequence of random numbers? The only correct answer: a sequence of random numbers is a sequence in which all elements are unrelated. This definition leads to the paradox that any sequence can be either random or non-random, depending on how the sequence is obtained. For example, the following string of numbers
1 2 3 4 5 6 7 8 9 0
was obtained by typing the top line of the keyboard in order, so the sequence cannot be considered randomly generated. But what if you get the same sequence when you take the numbered tennis balls out of the barrel. In this case, it is already a randomly generated sequence. This example shows that the randomness of a sequence depends on how it was obtained, and not on the sequence itself.

Remember that a computer-generated sequence of numbers is deterministic: each number except the first one depends on the numbers before it. Technically, this means that only a quasi-random sequence of numbers can be generated by a computer, i.e. in fact they are not truly random. However, this is sufficient for most tasks and for simplicity such sequences will be called random. One very interesting method was developed by John von Neumann; it is often called root mean square. In this method, the previous random number is squared, and then the middle digits are extracted from the result. For example, if you are creating numbers with three digits, and the previous number was 121, then squaring it gives the result 14641. Isolating the middle three digits gives the next random number 464. The disadvantage of this method is that it has a very short repetition period, called a cycle . For this reason, this method is not used today. Modern methods of generating random numbers are much more complex.

Random numbers in PHP

PHP has two groups of functions for working with random numbers. Purely externally, they can be distinguished by the mt_ prefix for all functions of one of the groups.

Deprecated features
rand function Returns an integer between zero and the value of RAND_MAX (which is 32767). Can have two optional integer parameters - if they are specified, a random number is generated from the first parameter to the second.

Echo rand(); echo rand(1,100); // Give out a random number from 1 to 100

Function srand. Specifies the sequence of random numbers produced by the rand function. It has an entire parameter - for different values ​​of this parameter, rand will produce different sequences of numbers. The srand function only needs to be called once before all calls to the rand function. Usage example:

Srand(1288); // Initialize the random number generator for($i=0; $iquery("SELECT COUNT(*) AS count FROM quotes");
if ($row = $sth->fetchRow()) (
$count = $row;
) else (
die ($row->getMessage());
}
$random = mt_rand(0, $count - 1);
$sth = $dbh->query("SELECT quote FROM quotes LIMIT $random,1");
while ($row = $sth->fetchRow()) (
print $row .

"\n";
}

This code snippet determines the total number of rows in the table, generates a random number from that range, and then uses LIMIT $random,1 to SELECT one row from the table starting at position $random. In MySQL version 3.23 or higher, an alternative option is possible:

$sth = $dbh->query("SELECT quote FROM quotes ORDER BY RAND() LIMIT 1");
while ($row = $sth->fetchRow()) (
print $row . "\n";
}

In this case, MySQL first randomizes the rows and then returns the first row.