简体   繁体   中英

How to generate a random 6-character string with alternating letters and numbers?

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

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:

i9f6q0
j4u5p4
j6l6n9

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

if(rand(0,1)){$string=strrev($string);}

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...

$letters=range('a','z'); // ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
shuffle($letters);
$numbers=range(0,9);  // [0,1,2,3,4,5,6,7,8,9]
shuffle($numbers);
$string='';
for($x=0; $x<3; ++$x){
    $string.=$letters[$x].$numbers[$x];
}
echo $string;

Try this code:

 $str = '';
 for ( $i = 1; $i <= 6; ++$i ) {
    if ( $i % 2 ) {
     $str .=  chr(rand(97,122));
    }else{
       $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.

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 .

You can use this function

<?php
 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)];
            }
        }
        shuffle($temp_array);
        return implode('', $temp_array);
    }
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM