php

How to Generate Random String in PHP

In this tutorial, we are going to see how to generate a random string in PHP. We can achieve that by storing all possible letters in a string and then generate a random index from 0 to the length of the string -1. As shown in the following code.
 

How to Generate Random String in PHP
<?php 

function getRandomStr($n) { 
    // Store all possible letters in a string.
    $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; 
    $randomStr = ''; 
  
    // Generate a random index from 0 to the length of the string -1.
    for ($i = 0; $i < $n; $i++) { 
        $index = rand(0, strlen($str) - 1); 
        $randomStr .= $str[$index]; 
    } 
  
    return $randomStr; 
} 

$n=25; 
echo getRandomStr($n); 

?>

 
Output:

E1fMe0TwBJVvpzBeO0zL0jFJw
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *