In your PHP application, you may be required to write an algo that generates random numbers that can be used for PINs, passwords, or some other purpose.
The maximum number in Windows platform can be (for example) 32768.
An example:
You may also specify a range for generating a random number e.g. 100 to 200.
This is done by using the optional parameters in the rand function as shown in the syntax below.
- Where $minimum number specifies the starting number for the random number to be generated.
- The $maximum specifies the highest number.
Both these parameters are optional, so you may omit and let the rand() function generate a number.
The section below shows using the rand function with and without parameters along with using rand multiple times for generating random numbers by the single statement – so keep reading.
The example of rand without parameters
In this example, the rand() PHP function is used without providing minimum or maximum numbers.
The random number is displayed by using PHP echo statement:
The code:
<?php echo "The random number without parameters: " .(rand()); ?>
As I executed this code in windows platform, the following was the output:
Using range for the random number
Now, I used the minimum and maximum parameters in the rand function.
The random number should be between 50 to 500. This is how it is specified:
Code:
<?php echo "The random number between 50-500: " .(rand(50,500)); ?>
Sample output:
Copy/Paste the above code to your editor and refresh the page to see what random number is displayed. This should be between 50 to 500 and change on every refresh.
A more usable example of rand function
In the following example, the rand function is used several times with different ranges to generate a number.
In that way, an accumulative number can be created based on certain rules.
- For example, the first part of the random code should be between 1-10.
- The second should be 100 to 1000 and then you may concatenate a fixed number etc.
PHP code:
<?php $gen_random = 420 .rand(25,50) .rand(100,1000) .rand(1000,10000) ; echo "Multiple rand number: " .$gen_random; ?>
The output as ran this code on the local system: