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';
$let
$let
to be 5 length : you need to loop 5 times and get 5 randoms charsJ
+ $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;
This means you only do one "random" function which is the shuffle and no looping in PHP.