Search code examples
phprandom

Generate alphanumeric string with 2 letters and 5 digits


I'm generating a unique 5 digit code using the following.

$randomUniqueNumber = rand(10000,99999);

I need to change this to an alphanumeric number with 5 digits and 2 letters.

The below gives me an alphanumeric number, but not restricted to just 2 letters.

$generated = substr(md5(rand()),0,5);

How would I generate a random string with 5 digits, and two letters?


Solution

  • There are probably a few ways to do it, but the following is verbose to get you going.

    <?php
    // define your set
    $nums = range(0, 9);
    $alphas = range('a', 'z');
    
    // shuffle sets
    shuffle($nums);
    shuffle($alphas);
    
    // pick out only what you need
    $nums = array_slice($nums, 0, 5);
    $alphas = array_slice($alphas, 0, 2);
    
    // merge them together
    $set = array_merge($nums, $alphas);
    
    // shuffle
    shuffle($set);
    
    // create your result
    echo implode($set); //86m709g
    

    https://3v4l.org/CV7fS

    Edit:

    After reading I'm generating a unique 5 digit code using the following. I suggest, instead, create your string by changing the base from an incremented value, rather than random (or shuffled) as you will undoubtedly get duplicates, and to achieve no dupes you would need to pre-generate and store your entire set of codes and pick from them.

    Instead look at something like hashids.