• Social Networks:

PHP to generate random string with format

Home » Blog » Programming & Tech » PHP to generate random string with format

Generated random string with format XXXX-XXXX-XXXX-XXXX a mix of numbers and letters.
In this example you can change $array_lengths = array(n,n,n,n); n = any numbers you can pass it will given your formatted numbers.

function randomString() {
    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array(); //remember to declare $pass as an array
    $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
    $array_lengths = array(4,4,4,4);
    foreach($array_lengths as $v){
      for ($i = 0; $i < $v; $i++) {
        $n = rand(0, $alphaLength);
        $pass[] = $alphabet[$n];
      }
      $pass[] = '-';
    }
    return rtrim(implode($pass),'-'); //turn the array into a string
}
echo randomString();

OR Simply you can generate random string with format XXXX-XXXX-XXXX-XXXX a mix of numbers and letters.

echo randomString(4)."-".randomString(4)."-".randomString(4)."-".randomString(4);
function randomString($chars) {
   $letters = 'abcefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
   return substr(str_shuffle($letters), 0, $chars);
}
Get Most Usefull Share Social Media

Request a free Quote to get started

We’re a professional bunch, and we want to work with you! Talk to us today to get started.