Home > Article > Backend Development > Pseudo-random number PHP random number generation code and usage example analysis
We can also use random numbers to design any program structure we can imagine.
First, let’s get to know the random number function rand() provided by PHP. PHP's rand() function will return a random integer. The specific usage is as follows
rand(min,max)
The optional parameters min and max can make rand() return a pseudo-random integer between 0 and RAND_MAX. For example, if you want a random number between 5 and 15 (inclusive), use rand(5, 15).
Let me look at a specific example below. We make a basic function call without setting specific parameters. The random number we get will not be limited by the min and max parameters.
Copy the code The code is as follows:
echo(rand());?>
Copy code The code is as follows:
echo(rand(1000,2000));?>
It’s simple enough, now let’s do something a little more difficult. At the beginning of this article, we said that random numbers are very useful. We can use PHP random numbers to solve some complex problems. 2. Use PHP to get a random element in a collection. Suppose we need to get a random element from an array
Copy the code The code is as follows:
$my_array=array('ASP','PHP', 'JAVASCRIPT','AJAX','CSS','JQUERY','HTML');
echo($my_array[rand(0,6)]);
?>
Copy the code The code is as follows:
$my_array=array('ASP','PHP','JAVASCRIPT','AJAX','CSS','JQUERY','HTML');
$ repetition=rand(0,6);
for($i=0;$i<=$repetition;$i++){
echo('I am learning ' . $my_array[rand(0,6)]);
echo(' on 51CTO.com');
}
?>
The results we get may look like the following:
The first time we run we get three results
Since we use a random The number limits the number of displayed items, so in addition to the random articles, the results are also random, as shown below:
The second run got seven results
Maybe you will ask, PHP random numbers only Can you do these boring things? rand() does not seem to be that important; you are wrong, think about the verification codes that can be seen everywhere, the random article extraction of some CMS systems, download address allocation, etc. Random numbers are used in these applications Play an important role; in addition, in the fields of security and algorithms, many applications of random numbers are also worthy of our in-depth study, such as encryption and congruence structures.
The above introduces the pseudo-random number PHP random number generation code and usage example analysis, including pseudo-random number content. I hope it will be helpful to friends who are interested in PHP tutorials.