Computers Windows Internet

Using the PHP random function. Random selection from array in php php random integer

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

Randomness and uniqueness

PHP's random function comes in two flavors: rand () and mt_rand (). It is believed that the algorithm in the first case is simpler and generates pseudo-random numbers. The second option has a faster algorithm and 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 the 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 alphabetical information, for example, for testing communication channels or algorithms.

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

Using the time function

The function of time, 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 random value will be repeated.

By applying PHP random over a range of seconds or milliseconds over a wide range of possible values, you can get unique random combinations of numbers or letters. What else?

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

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

Hello everyone! In this article, we will look at what's new for generating random numbers in PHP 7.1.

This update happened invisibly to developers, but improved the programming language PHP in the field of generating random numbers.

As far as is known, in PHP we can use the function rand (min, max) to generate random numbers:

Echo rand (7, 17);

If you refresh the page now, you will receive a new random number each time.

But not everything is as simple as it might seem. The point is that depending on what you are generating the random number for, the function rand () uses different systems generation. Those. it depends on the system in which it is used. Some systems can use weak methods of generation, respectively, you will receive not entirely random numbers.

V PHP 7.1 this issue has been fixed and the function has been added mt_rand ():

Echo mt_rand (7, 17);

This feature works much better, including security. What's also important to know is that if you use the function rand () v PHP 7.1, then it will automatically be overwritten to mt_rand ()... Those. rand () now just an alias for mt_rand ().

Many other functions for obtaining random results have been improved in PHP 7.1... For example, let's see how we can get a random value from an array:

$ names = ["Ivan", "Alexander", "Vasiliy"];
echo $ names;

Those. any functions such as this have been improved to produce better quality random numbers in PHP 7.1... Yes, this update went unnoticed, but no matter what language you write in, it is very important to understand what happens inside a function and how it behaves.

Task
You need to generate a random number within a numeric range.

Solution
This is what the mt_rand () function is for:

// random number between $ upper and $ lower, inclusive
$ random_number = mt_rand ($ lower, $ upper);

Discussion
Random number generation is useful when you need to display a random picture, randomly assign a starting point in the game, select a random entry from the database, or generate unique identificator session. In order to generate a random number between two points, you need to pass two arguments to the mt_rand () function:

$ random_number = mt_rand (1, 100);

Calling mt_rand () with no arguments returns a number between zero and the maximum random number returned by mt_getrandmax (). It is difficult for a computer to generate a truly random number. He is much better at following instructions methodically and is not so good at spontaneous actions required of him. If you need to force the computer to produce a random number, then you need to give it a certain set of repeatable commands, while the very fact of repetition makes the achievement of randomness less likely.

PHP has two different random number generators: the classic function called rand () and the more advanced mt_rand () function.

MT (Mersenne Twister) is a pseudo-random number generator named after the French monk and mathematician Marin Mersenne, who studied prime numbers. The algorithm of this generator is based on these primes. The mt_rand () function is faster than the rand () function and produces more random numbers, so we prefer the former.

If your PHP version is earlier than 4.2, then before calling the mt_rand () (or rand ()) function for the first time, you need to initialize the generator with an initial value by calling the mt_srand () (or srand ()) function. The seed is the number that the random function uses as the basis for generating the random numbers it returns; it refers to a way of resolving the above dilemma - repetition versus randomness.

As an initial value that changes very quickly and with a low probability of repeatability (these properties should characterize a good initial value), you can take the value returned by the high-precision time function microtime (). It is enough to initialize the generator once. PHP 4.2 and later automatically handles initialization, but if the initial value is manually set before the first call to mt_rand (), then PHP will not replace it with its own initial value.

If you need to select a random record from the database, the easiest way is to first determine the total number of fields in the table, select a random number from this range, and then query this row from the database:

$ sth = $ dbh-> query ("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 $ random. In MySQL version 3.23 or higher, an alternative 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 randomizes the rows first and then returns the first row.

I've already been asked a couple of times how I do random output of quotes on my website in the block " Smart quotes". Further, I managed to find out that the problem here is a lack of understanding of people, how to deduce random element from array in php... The task is simple, but nevertheless, since questions arise, you need to answer them.

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

$ quotes = array (); // Initialize an empty array
$ quotes = "Be attentive to your thoughts, they are the beginning of actions."; // First quote
$ quotes = "It is not the smartest or the strongest that survives, but the most susceptible to change."; // Second quote
$ quotes = "Life is a mountain: you go up slowly, go down quickly."; // Third quote
$ quotes = "People don't want to be rich, people want to be richer than others."; // Fourth quote
$ number = mt_rand (0, count ($ quotes) - 1); // Take a random number from 0 to (array length minus 1) inclusive
echo $ quotes [$ number]; // Display the quote
?>

Key moment- this is getting a random number... All you have to do is set the correct boundaries. If you need to select a random element along the entire length of the array, then this is from 0 before ( array length minus 1). And then just pull the element out of the array with the resulting random index.

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