PHP code for generating decent-looking coupon codes (mix of letters and numbers)

前端 未结 10 1438
后悔当初
后悔当初 2020-12-15 21:56

For an ecommerce site I want to generate a random coupon code that looks better than a randomly generated value. It should be a readable coupon code, all in uppercase with n

10条回答
  •  不知归路
    2020-12-15 22:41

    $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $res = "";
    for ($i = 0; $i < 10; $i++) {
        $res .= $chars[mt_rand(0, strlen($chars)-1)];
    }
    

    You can optimize this by preallocating the $res string and caching the result of strlen($chars)-1. This is left as an exercise to the reader, since probably you won't be generating thousands of coupons per second.

提交回复
热议问题