random_int function & for loop

<?php

function generateRandomString(int $length): string
{
    $chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $maxIdx = strlen($chars) - 1;

    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $idx = random_int(0, $maxIdx);
        $randomString .= $chars[$idx];
    }

    return $randomString;
}

$randomString = generateRandomString(10);
echo $randomString;

Leave a Comment

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