PHP rand function
You can create a random string in PHP using the rand function. A random string may be a complex password, a verification code, or anything else. Automating random string can save time and reduce the manual process in applications. Rather than creating your own logic of random strings, we can use the rand funtion.
In this step by step tutorial, I'll create and use a random string in PHP.
Step 1. Create a PHP rand_string function
First, create a PHP function with one (1) parameter specifying the length of the random string to be created.
- function rand_string ($length){...body}
It is used to generate a random string.
Step 2. Declare a Variable
Let's declare a string variable with the name of char.
- $char="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";
It contains a collection of various types of strings. When a function generates a random string, all of the characters are fetched from it.
Step 3. Random generator
We will refer to parts of this String using a random generator. Once we generate a random integer index, we add the corresponding character – the character at that index – to a finished String. This can be completed using a loop:
- $size = strlen( $chars );
- for( $i = 0; $i < $length; $i++ ) {
- $str= $chars[ rand( 0, $size - 1 ) ];
- echo $str;
- }
Step 4. Call rand_string() function
rand_string( 5 );
PHP rand Example
Here is the comple code example.
- <?php
- function rand_string( $length ) {
- $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@#$&*";
- $size = strlen( $chars );
- echo "Random string =";
- for( $i = 0; $i < $length; $i++ ) {
- $str= $chars[ rand( 0, $size - 1 ) ];
- echo $str;
- }
- }
- rand_string( 5 );
- ?>
Note: the above example will not work when the length is greater then $char string length.
This is what the output looks like:
Summary
PHP rand function is used to generate random strings in PHP. In this article, we saw how to use the rand funtion in PHP to generate random strings.