randstr php code example

Example 1: PHP random string generator

function generateRandomString($length = 25) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
//usage 
$myRandomString = generateRandomString(5);

Example 2: php random number

// $min and $max are optional
rand($min,$max);

Example 3: php random integer

echo random_int(0,50);

Example 4: php random number

rand(0,10);
or
random_int(0,10)

Example 5: randstring php

<?php 
    $random = substr(md5(mt_rand()), 0, 7);
    echo $random;
?>

Tags:

Php Example