Home > database >  How to generate a random unique alpha string in PHP or Laravel?
How to generate a random unique alpha string in PHP or Laravel?

Time:11-25

I would like to generate a random unique alpha string in PHP or Laravel, that would it be only 5 characters long, the problem is that in all the examples I've found, they mention how to generate alpha-numeric strings, and I need only alpha characters, and also it to be upper case, how can I do it? thank you.

CodePudding user response:

Str::random(5) can be used to generate non-unique alpha-numeric strings, but if you want unique, alpha only, then you'll need some kind of helper function.

Laravel's Collection class has a number of methods that makes this rather trivial:

public function randomString() {
  $alphaString = collect(array_merge(range('a', 'z'), range('A', 'Z')))
  ->shuffle()
  ->take(5)
  ->implode('');
}

This will generate 5 character alpha strings (without repeating values, that can be done too if you need more combinations), but still doesn't handle the "unique" part. To handle that, you simply need to check the generated value, and regenerate it if it already exists somewhere. A common use-case is using this value as a unique column for a Model:

public function randomString() {
  $alphaString = collect(array_merge(range('a', 'z'), range('A', 'Z')))
  ->shuffle()
  ->take(5)
  ->implode('');

  if (Model::where('column', $alphaString)->exists()) {
    return $this->randomString();
  }

  return $alphaString;
}

If you want to allow repeated values, then you'd need to loop and shuffle:

public function randomString() {
  $values = collect(array_merge(range('a', 'z'), range('A', 'Z')));

  $characters = collect();
  while ($characters->count() < 5) {
    $characters->push($values->shuffle()->first());
  }
  
  $alphaString = $characters->implode('');

  if (Model::where('column', $alphaString)->exists()) {
    return $this->randomString();
  }

  return $alphaString;
}

This allows for more combinations, but you're still rather limited with only 5 characters.

Edit: If you're not using Laravel, native array methods work too, as the Collection class is basically just a fancy array anyway:

$values = array_merge(range('a', 'z'), range('A', 'Z'));

$characters = [];
while (count($characters) < 5) {
  shuffle($values);
  $characters[] = $values[0];
}
  
$alphaString = implode($characters);

And, bonus, an interactive version to verify:

https://3v4l.org/tR5IF#v8.1.13

  • Related