Home > Software design >  Name generator specific first letter
Name generator specific first letter

Time:11-21

I created a name generator that works fine but now I would like for the results of my random words to start by a specific letter let's say "S" so all the results will always start by the letter "S".

Here is my code so far :

<?php
function getRandomWord($len = 7) {
  $word = array ( "exemple" ,"1");
  shuffle($word);
  return substr(implode($word), 0, $len);
}

for ($i = 0; $i < 30; $i  ) {
  echo getRandomWord(). "\n";
}

Thanks!

My code works fine, I just don't know how to force it to be created by a certain letter as a first letter.

CodePudding user response:

You can try this one:

function getRandomWord($len = 7, $start = 'S') {
  $word = array_merge(range('a', 'z'), range('A', 'Z'));
  shuffle($word);
  $word = $start . substr(implode($word), 0, $len - 1);
  return $word;
}

for ($i = 0; $i < 30; $i  ) {
  echo getRandomWord() . "<br>";
}

// output

SgmIuSb
SWpYANu
SxRqWBt
SvYpOQb
SPQlWfJ
SvUjmbM
SjxUmYv
SBaPxEd
SzYrqVU
SLojCPs
SwFRCSv
SiCpkxo
SmDdaGL
SSLcilq
SXQoLkr
SnHZAUE
SuaIszy
SyJGwlO
Svdbijp
SSXHUOp
SpeMAuv
SgtpTBi
SmoLstC
SaGtlHR
SEABDCs
SdDphmZ
SAHwquP
SRANhwe
SBmwRgU
SMHXYQL

just pass the character in $start parameter that you want.

  •  Tags:  
  • php
  • Related