在PHP中生成唯一字母表时出现问题

Am trying to generate a unique value in PHP where the first and last letters should be J and 1 respectively while the middle characters should be a series of aplhabetical letters and the whole value should be 7 in total eg JWERYH1 Please assist?

$let = chr(rand(65, 90));

$all = 'J' . $let . '1';

dd($all);

Try this code

$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "";
for ($i = 0; $i < 5; $i++) {
    $res .= $chars[mt_rand(0, strlen($chars)-1)];
}

echo 'J'.$res.'1';

Try this :

$let = "";
for ($i=0; $i<5; $i++) {
    $let .= chr(rand(65, 90));
}
$all = 'J' . $let . '1';
  1. You prepare an empty var $let
  2. You need a 7 lenght var with 2 fixed char (J and 1) so you need $let to be 5 length : you need to loop 5 times and get 5 randoms chars
  3. Now you get your 7 lenght string with J + $let + 1

Eg. of result after 5 attempts :

JJGBIP1
JRPYGO1
JBONBW1
JCLVSY1
JRDHGI1

You can create an array of all the letters with range().
Then shuffle it and extract the first five letters and use implode to make them a string.

$letters = range("A", "Z");

shuffle($letters);

$all = 'J' . implode("",array_slice($letters,0,5)) . '1';
echo $all;

https://3v4l.org/KuZ2H

This means you only do one "random" function which is the shuffle and no looping in PHP.