Skip to content

All topics  /  PHP

How to Generate random a String In PHP

PHP ·

Hi Guys,

In this example,I will leran you how to generate random string in php.you can simply and easy to generate random string in php.

For Example,random function is first argument how to get character for string and second argument length to string.bellow example

Example :


<?php 

 
function RandomStringGenerator($length) 
{ 
    // Variable which store final string 
    $randomString = ""; 

      
    // small letters, capital letters and digits
    $characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; 

      
    // Find the length of created string 
    $len = strlen($characters); 

      
    // Loop to create random string 
    for ($i = 0; $i < $length; $i++) 
    { 
        // Generate a random index to pick 
        $index = rand(0, $len - 1); 

          
        // Concatenating the character  
        $randomString = $randomString . $characters[$index]; 
    } 

      
    return $randomString; 
} 

  
$length = 10; 
echo "Random String of length " . $length 
   . " = " . RandomStringGenerator($length); 
?> 

It will help you.....