Generate random string in PHP

0
169
PHP

This example explains how to generate random string in PHP using function.

<?php
function generate_id($length = 10) {
    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$random_string=generate_id(4); //value is optional if value is not given then function will take value as 10.
?>

The above function will generate the random string of length 4. you can change the length as per your requirement.

LEAVE A REPLY

Please enter your comment!
Please enter your name here