dcolumbus
dcolumbus

Reputation: 9722

Random coupon code, make sure they're all unique

My code:

echo "<table width='200px' cellpadding='5' cellspacing='0'><tbody>";

$total = 500;
for ($j = 0; $j < $total;$j++) {
    echo "<tr>";
    echo "<td>" . ($j+1) . "</td>";
    echo "<td>" . get_coupon_code() . "</td>";
    echo "</tr>";
}

function get_coupon_code() {
    $characters = 'ABCDEFGHJKLMNPQRSTUZWXYZ';
    $random_string_length = 8;
    $string = '';
    for ($i = 0; $i < $random_string_length; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
    return $string;
}

echo "</tbody></table>";

What would be the way to ensure that each code that's generated is unique?

Upvotes: 1

Views: 1586

Answers (2)

SaidbakR
SaidbakR

Reputation: 13544

use static array variable to store your coupon codes and before returning the code ensure that it is not available in the array. Or more simpler, store the codes in an array handled in a session.

function get_coupon_code() {
$arr = $_SESSION['codes'];
    $characters = 'ABCDEFGHJKLMNPQRSTUZWXYZ';
    $random_string_length = 8;
    $string = '';
    for ($i = 0; $i < $random_string_length; $i++) {
        $string .= $characters[rand(0, strlen($characters) - 1)];
    }
if (is_array($arr) && in_array($string, $arr))
{
return get_coupon_code();
}
else{
$_SESSION['codes'][] = $string;
    return $string;
}
}

Edited adding return to inner call of get_coupon_code()

Upvotes: 0

Thomas Kelley
Thomas Kelley

Reputation: 10302

The only true way to make sure you don't duplicate codes is to save them into a database, a file, or to keep them in memory (if the duration is short).

You might also want to check out PHP's uniqid() function:

print_r( uniqid() );

// Sample output:
//
// 50c65cefe58b1

But this might not meet your solution, since (a) it's still not guaranteed to be entirely unique, and (b) it introduces numbers to the code (not just letters).

Documentation: http://php.net/manual/en/function.uniqid.php

Upvotes: 1

Related Questions