php random 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: random number generator in php

you can use rand() function for that in php.
Example:
Generate random numbers between 1 to 50
<?php
  echo rand(1,50);
?>

Example 3: php random number

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

Example 4: php random string

function rand_str() {
    $characters = '0123456789-=+{}[]:;@#~.?/&gt;,&lt;|\!"£$%^&amp;*()abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $randomstr = '';
    for ($i = 0; $i < random_int(50, 100); $i++) {
      $randomstr .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $randomstr;
  }

Example 5: php random number generator

<?php
  echo rand(1,50);
?>

Example 6: php random

mt_rand(1000, 9999)

Tags:

Java Example