I have a code in PHP that is able to generate a 6-character alpha-numeric string but it does not ensure that there are 3 letters and 3 numbers generated.

It generates a string such as "ps7ycn" It does not have 3 numbers in between the alphabet. The numbers should be in between the letters.

example : a3g5h9

  • 2
    where is your code? – Alexan Aug 14 '17 at 3:00
  • Can the numbers or letters be duplicated? Is this okay: 3r3r3r? Do the character types need to alternate or is this valid: 123abc? Did you search for pre-existing answers on SO before posting your question? – mickmackusa Aug 14 '17 at 4:16
  • Welcome to StackOverflow. Please read and follow the posting guidelines: what kinds of questions can I ask stackoverflow.com/help/on-topic, and How to ask: stackoverflow.com/help/how-to-ask Remember to also to include Minimal, complete, verifiable examples: stackoverflow.com/help/mcve. Then, click edit to edit your question so that we may help. – SherylHohman Aug 14 '17 at 4:51

This will ensure you only get alternating letters and numbers:

Code: (Demo)

$letters='abcdefghijklmnopqrstuvwxyz';  // selection of a-z
$string='';  // declare empty string
for($x=0; $x<3; ++$x){  // loop three times
    $string.=$letters[rand(0,25)].rand(0,9);  // concatenate one letter then one number
echo $string;

Potential Outputs:


p.s. If you want to randomize whether the first character is a letter or number, use this line of code after the for loop.


rand() will generate a 0 or a 1, the conditional will treat 0 as false and 1 as true. This offers a "coin flip" scenario regarding whether to reverse the string or not.

If you want to guarantee unique letters and numbers in the output...

$numbers=range(0,9);  // [0,1,2,3,4,5,6,7,8,9]
echo $string;

Try this code:

 $str = '';
    if ( $i % 2 ) {
     $str .=  chr(rand(97,122));
       $str .= rand(0,9);

This one is shorter but you can not use it to have odd length like a1g7y5k :

$str = '';
 for ( $i = 1; $i <= 3; ++$i ) {
  $str .=  chr(rand(97,122)) . rand(0,9);

-Alternatively use this method that can be improved ( refer to mickmackusa's comments):

$alphas  = 'abcdefghijklmnopqrstuvwxyz';
$numbers = '0123456789';
$arr1 = str_split($alphas);
$arr2 = str_split($numbers);
$arr3 = array_rand($arr1,3);
$arr4 = array_rand($arr2,3);
$arr5 = array();
for ($i=0; $i<count($arr3); $i++) {
   $arr5[] = $arr3[$i];
   $arr5[] = $arr4[$i];
$result =    implode('',$arr5);

Check this thread.It has some good ideas and functions.

  • While these snippets generate the expected result, I have some important notes to make for Amr and future readers... – mickmackusa Jan 28 '18 at 12:12
  • The first method is certainly the better of the two because it generates the output string without a lookup array or array functions. The modulo conditional is used every iteration to determine odd/even. Because this method is already using concatenation to build the string and each letter is trailed by a number, it would be better to omit the conditional entirely and just concatenate the number after the letter (as I have posted in my answer). If you still want to determine odd/even, the bitwise & operator is a better call (php.net/manual/en/language.operators.arithmetic.php#120654). – mickmackusa Jan 28 '18 at 12:13
  • The use of chr() is noteworthy because it avoids the literal string declaration, but the link that you provided is a perfect argument for why you shouldn't use an ascii referencing function call (increased risk of developer error, and decreased code comprehension/maintainability). The trade off, otherwise, comes down to omitting the lookup string declaration and making iterated chr() calls. – mickmackusa Jan 28 '18 at 12:13
  • 1
    Its about flexibility. – Amr Berag Jan 29 '18 at 1:23
  • 1
    IMHO the question is mainly about generating alternating alphanumeric strings and the length should be optional and even more options should be possible like controlling the frequency and length of each domain. – Amr Berag Jan 29 '18 at 1:54

Here's one way you could address this:

$alpha  = 'abcdefghijklmnopqrstuvwxyz';
$number = '0123456789';

$random = '';

for ( $i = 0; $i < 6; ++$i ) {
    if ( $i % 2 ) {
        $random .= substr( $number, rand( 0, strlen( $number ) - 1 ), 1 );
    } else {
        $random .= substr( $alpha, rand( 0, strlen( $alpha ) - 1 ), 1 );

$random will now contain a six-character random value with the first, third, and fifth characters coming from $alpha and second, fourth, and sixth characters coming from $number.

  • @mickmackusa I'm assuming that you're the downvoter given your comments on the answer that plagiarized my answer. Care to explain the downvote? – Nick Coons Aug 15 '17 at 20:31
  • 1
    Upvoting this for using the modulo. This allow to have a code with odd length. – Amr Berag Jan 28 '18 at 17:51
  • I have corrected the loop in this answer, but will not be upvoting it because calling the modulo conditional, substr(), and strlen() on each iteration is unnecessary for this task. – mickmackusa Jan 29 '18 at 0:46

You can use this function

 public static function random_string($charsNo = 3, $NumbersNo = 3)
        $character_set_array = array();
        $character_set_array[] = array('count' => $charsNo, 'characters' => 'abcdefghijklmnopqrstuvwxyzasdsawwfdgrzvyuyiuhjhjoppoi');
        $character_set_array[] = array('count' => $NumbersNo, 'characters' => '0123456789');
        $temp_array = array();
        foreach ($character_set_array as $character_set) {
            for ($i = 0; $i < $character_set['count']; $i++) {
                $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
        return implode('', $temp_array);
  • 1
    Because it never changes, calling strlen() on every iteration is not best practice. You'd be better off creating another element in your multi-dimensional array that stores length. The empty array declarations are unnecessary. Also, when gluing together array elements with an empty string, the first parameter can be omitted. See my answer. – mickmackusa Aug 14 '17 at 4:59
  • I made the same mistake as you in my earlier post in assuming that the six numbers and letters needed to be shuffled (for maximum randomness). However, this is not what the OP is asking for. The question states that the three letters should be separated by numbers. – mickmackusa Aug 14 '17 at 6:19
  • Why did you jam "gobbledygook in your characters element where 26 alphabetical letters are meant to be? You are adding undesirable weight to the probability of certain letters. I am downvoting this answer because it doesn't provide the output that the OP has requested. sandbox.onlinephpfunctions.com/code/… – mickmackusa Jan 27 '18 at 21:22

Your Answer

