Random selection from an array in PHP. Random numbers Random number php

Random selection from an array in PHP. Random numbers Random number php

22.11.2023

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

This update happened invisible to developers, but improved the programming language PHP in the field of random number generation.

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 now refresh the page, 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 generation systems. Those. it depends on the system in which it is used. Some systems may use weak generation methods, so you will receive numbers that are not entirely random.

IN PHP 7.1 this problem has been fixed and a feature has been added mt_rand():

Echo mt_rand(7, 17);

This feature works much better, including security. What is 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 random results features have been improved in PHP 7.1. For example, let's look at 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 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 is happening inside a function and how it behaves.

I've already been asked a couple of times how I'm doing random output of quotes on my website in the block " Smart Quotes". Next, I managed to find out that the problem here is with people’s misunderstanding, how to get 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:

$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 who survive, but the most receptive to change."; // Second quote
$quotes = "Life is a mountain: you go up slowly, you 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]; // Output the quote
?>

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 this is from 0 before ( array length minus 1). And then just pull 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 V SQL query, so that you immediately receive a single and random quote from the database.

Now we take a ready-made password generation function and write a script to recover or create a new password for users of your site.

Password recovery script

How is the script usually written?

As always, a step-by-step scheme is drawn up, what we must do step by step. Everything happens in one file, reminder.php

1. We run the script only if there is a certain variable, for example $action;

2. To start the password generation process, the user specifies the email address $_POST[`ema‘l`]; To simplify the code, let's assign this value to the $email variable.

3. Using regular expressions, we check all the characters to ensure that the user has entered the correct email address. If not, we display an error and stop the script. If everything is correct, we move on.

4. We look in the database, in our case in the users table, for a user with this email address. If not, we issue an error that there is no such address in the database and stop the script.

5. There is a user with this address in the database, go ahead and launch the function of generating a new password. Also, using the email address, we get the user’s unique id from the database and write it to the $id variable;

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

Solution
The mt_rand() function is designed for this:

// 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 on the screen, randomly assign a starting point in a game, select a random entry from a database, or generate a unique session identifier. In order to generate a random number in the interval 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 if he is required to act spontaneously. If you need to force a computer to produce a random number, then you need to give it a certain set of repeatable commands, and the very fact of repeatability makes achieving randomness less likely.

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

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 prime numbers. The mt_rand() function is faster than the rand() function and produces more random numbers, so we prefer the former.

If you have a version of PHP 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 dilemma mentioned above – repeatability versus randomness.

As an initial value that changes very quickly and with a low probability of repeatability (these properties should be characterized by 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 set manually before the first call to mt_rand(), PHP does not replace it with its own initial value.

If you need to select a random record from a database, the easiest way is to first determine the total number of fields in the table, select a random number from that range, and then query that 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 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.

© 2024 hecc.ru - Computer technology news