You are here: Home / Topics / How to Generate Random String in PHP

How to Generate Random String in PHP

Filed under: PHP on 2022-10-30 20:51:33

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.

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 will be:

C7sXCEsWsXZHWztywCdWtnqZm

Generate Random string Online | Want to learn and practice PHP MCQs

About Author:
T
Team MCQ Buddy     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.