view raw
Dimitar Mitov Dimitar Mitov - 11 months ago 29
PHP Question

iPHP Generate 2 letters based on number

I am trying to generate some SKU numbers and I came to an issue that has made me think, and as I slept less than 2 hours I decided to ask you guys, Stackoverflowers.

Let's say I've got an array of the alphabet excluding commonly mistaken letters.

$alphabet = array("A","C","D","E","F","G","H","I","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z");

I am trying to generate 2 letters based on consistent number. Let's say I've got sub-products that I want to have that suffix in the end of their SKU. For the first sub-product the SKU will have suffix - AA, for the 24th - AZ, 25th - CA, 26th - CC and so on. The thing is that we don't want to have repeating suffixes, but AC and CA are acceptable.

Thank you for doing the dirty job for a sleep needing programmer.

Making it clear:
I want to get a combination based on irritation. Let's say:

$i = 1, then $suffix = AA;
$i = 2, then $suffix = AC;
$i = 24, then $suffix = ZZ;
$i = 25 (one above the count of the array), then $suffix = CA;
$i = 26, then $suffix = CC;
$i = 49, then $suffix = DA (**I suppose**)

Let's say I have sub-products for product 1 and sub-products for product 2. Product 1's sub-products' suffixes should be:

AA, AC, AD, AE .... AZ, CA, CC, CD .... CZ .... ZA, ZC ... ZY.

Product 2's sub-products' suffixes can also be the same!


I would use the product number to pick two indexes from the list of available letters The following can be done in one line, but I expand it so I can explain what it does.

function get2letter($num)
    $alphabet = array("A","C","D","E","F","G","H","I","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z");
    $code = $alphabet[$num%sizeof($alphabet)]; // Get the first letter
    $num = floor($num/sizeof($alphabet)); // Remove the value used to get the first letter
    $code.= $alphabet[$num%sizeof($alphabet)]; // Get the second letter
    return $code;

for($i=0; $i<10; $i++)
    print get2letter($i)."\n";

This will work for small values. You have collisions when you surpass the number of unique values you can represent with your alphabet.