Nits Nits - 6 months ago 10
PHP Question

How to create 7 digits alphanumeric in PHP for coupons?

How to create 7 or Nth digits alphanumeric coupon code in a fast way? I have checked to use

array_rand
or
rand
or
mt_rand
which function should I prefer. To make my code fast and get more random number.

Requirement:


  1. It should be take random number from 0-9 and A-Z (not lowercase a-z).

  2. Starting first to three characters should be from A-Z and remaining should be 0-9.

  3. 0-9 and A-Z can be repeat.


Answer

Requirement:
1) It should be take random number from 0-9 and A-Z ( not lowercase a-z).
2) Starting first to three characters should be from A-Z and remaining should be 0-9.
3) 0-9 and A-Z can be repeat.

You can use substr() and str_shuffle, i.e.:

$partOne =  substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 3);    
$partTwo =  substr(str_shuffle("0123456789"), 0, 4);  
echo $partOne.$partTwo;
//ZPN1690

Ideone Demo:

http://ideone.com/OU3DuM