Search code examples
phparraysfor-looprangegenerated

PHP create exact key string from array values by provided ID and length


Hi everyone i really need help with my final coding for my Generator.

TO DO :
There need to be some reverse way of doing this :
8 length generated code


    0000 0000 = Code Number 0
    0000 0001 = Code Number 1
    0000 0158 = Code Number (1 * 10^2) + (5 * 10^1) + (8 * 10^0) = 158

    For Alphabets (A=0, B=1, C= 2, ... Z = 25, a = 26, ..., z = 51, 0 = 52, 1 = 53, 9 = 61:
    AAAA ABCD = Code Number (0 * 62^7) + (0 * 62^6) + (0 * 62^5) + (0 + 62^4) + (0 * 62^3) + (1 * 62^2) + (2 * 62^1) + (3 * 62^0) = 14780307

This is the current way :
generate key -> count the possicion of the key

Solution wanted :
input ID -> generate key without too much cycling by PHP "for" cycle

At the moment if i input ID 5,000,000 with proper setting the script hang up or the page will become unavailable.
I haven't found any simple solution of how to reverse it,
but i believe there must be somethnig to solve this issue.
So if anyone know a solution please feel free to develop and commit. Thanks

Click here to see the BaseCode


Solution

  • I've found similar solution here at github and after understanding the code i have created
    working PHP example :

    
    
        // Digital number  -->>  AlphaNum code
                $code_id = 1;
                $code_length = 8;
                $characters_range = array_merge(range('A','Z'), range(0,9));
                $characters_count  = count($characters_range);
                $code_max_id = bcpow($characters_count, $code_length);
                echo $code_max_id;
                echo "\n";
                for($length=($code_length-1);$length>=0;$length--){
                    $possition = floor($code_id / bcpow($characters_count, $length));
                    $code_id = $code_id - ($possition * bcpow($characters_count, $length));
                    $character_keys[] = $characters_range[$possition];
                }
                //Choose which one to use
                //echo implode($character_keys);
                print_r($character_keys);
    
    

    Here is a Czech website with the same thread.
    So now i can finalise my CANG("Complex Alpha-Numeric Generator") without any trouble.