Generate a random string

PHP 8.3 introduced the Randomizer::getBytesFromString() method, which allows you to generate a random string from the specified characters.

$availableChars = 'abcdefghijklmnopqrstuvwxyz0123456789@1#$%^&*';

$randomizer = new \Random\Randomizer();
$randomizer->getBytesFromString($availableChars, 16); // v@1yuyzb0#py09u1
$randomizer->getBytesFromString($availableChars, 16); // $uy5qb*bzdcv$chh

This function can be useful when you need to, for example, generate a random password for a user.

If you are using PHP version lower than 8.3, you can create your own function:

function getRandomString($count) {
    $availableChars = 'abcdefghijklmnopqrstuvwxyz0123456789@1#$%^&*';
    $charsLength = mb_strlen($availableChars);
    $randomString = '';
    for ($i = 0; $i < $count; $i++) {
        $randomString .= $availableChars[random_int(0, $charsLength - 1)];
    }
    
    return $randomString;
}

getRandomString(16); // p1b5eq9sd7sw&cvc
getRandomString(16); // o^g#9fh$^81z49u1

The two methods above do not support Unicode.

Unique String

You can generate a unique string (which will definitely not be repeated when regenerated) using the uniqid() function.

echo uniqid(); // 69689c745ceb8
echo uniqid(); // 69689c7819d8f

The string is generated based on the current time, so it is always unique.