How to Generate random a String In PHP

Share Me
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

Today now in this example,I will show you how to generate random string in php. From here you can know how to simply and easily generate random string in php.

Now for Example,random function is first argument then how to get character for string and then the second argument is length to string. Now here the 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); 
?> 

Read Also : Laravel 8 Eloquent Global Scope Tutorial Example

I hope it will help you. Also you can follow us on Facebook

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →