How to generate a random string in PHP?

In this blog, we will see how we can generate a unique random string by creating a custom PHP function and we can use it anywhere in our code like to create the URL slug, for SEO purposes, etc.

Here is the simplest method that can be achieved by following the steps below:

  • Storing all the possible letters into strings.
  • Generating a random index from 0 to the length of the string -1.
  • Printing the letter on the given index.
  • Implementing the steps n times also n is considered the length of the required string.

Example :

<?php
$n=10;
function getRandomString($n) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomString = '';
  
    for ($i = 0; $i < $n; $i++) {
        $index = rand(0, strlen($characters) - 1);
        $randomString .= $characters[$index];
    }
  
    return $randomString;
}
  
echo getRandomString($n);

?>

OutPut : yE23RQE7eW

So, thanks for following this blog, and if you need any help please leave your queries in the comment box we will be happy to help you.

How to generate a random string in PHPexpoundsofttechsolution

ghb