1

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?

  • 2
    Possible duplicate of [PHP component that generares random string from regex](https://stackoverflow.com/questions/21030978/php-component-that-generares-random-string-from-regex) `[0-9]{5}[a-z]{2}` would work – Zoe Edwards Oct 10 '18 at 08:25
  • 1
    Is this for creating a password? If yes, have it look at [this question](https://stackoverflow.com/questions/1837432/how-to-generate-random-password-with-php). – Karsten Koop Oct 10 '18 at 08:25

1 Answers1

4

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.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106