Saswat - 3 months ago 19
PHP Question

# How to create 6 digit OTP with 2 digits and 4 alphabets?

I have a script which generates 6 character One Time Password (OTP).

Here is the code:-

``````\$seed = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.'0123456789'); // and any other characters
shuffle(\$seed); // probably optional since array_is randomized; this may be redundant
\$rand = '';
foreach (array_rand(\$seed, 6) as \$k)
\$rand .= \$seed[\$k];
\$feedID = \$rand;
``````

Now, due to shuffling procedure, currently all 6 can be digits, all 6 can be alphabets.
I want min and max 2 mandatory digits.

How can I do that?

Here's my take on it:

``````// Create a string of all alpha characters and randomly shuffle them
\$alpha   = str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ');

// Create a string of all numeric characters and randomly shuffle them
\$numeric = str_shuffle('0123456789');

// Grab the 4 first alpha characters + the 2 first numeric characters
\$code = substr(\$alpha, 0, 4) . substr(\$numeric, 0, 2);

// Shuffle the code to get the alpha and numeric in random positions
\$code = str_shuffle(\$code);
``````

If you want the possibility to have any character more than once, change the two first lines (quick and dirty):

``````// Let's repeat this string 4 times before shuffle, since we need 4 characters
\$alpha   = str_shuffle(str_repeat('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 4));

// Let's repeat this string 2 times before shuffle, since we need 2 numeric characters
\$numeric = str_shuffle(str_repeat('0123456789', 2));
``````

Not saying that this is the best way of doing it, but it's simple, without loops and/or arrays. :)