phpiban

Optimize PHP script for generating IBAN


I wrote function in PHP that generates croatian IBAN for given bank account. I can easily rewrite for returning any IBAN. Problem is that I think it is not optimized nor elegant. This is the function:

function IBAN_generator($acc){

    if(strlen($acc)!=23)
        return;
    $temp_str=substr($acc,0,3);
    $remainder =$temp_str % 97;
    for($i=3;$i<=22;$i++)
    {
        $remainder =$remainder .substr($acc,$i,1);
        $remainder  = $remainder  % 97;
    }
    $con_num = 98 - $remainder;
    if ($con_num<10)
    {
        $con_num="0".$con_num;
    }
    $IBAN="HR".$con_num.substr($acc,0,17);
    return $IBAN;
} 

Is there a better way to generate IBAN?


Solution

  • At first glance it doesn't seem you can make it much faster, it's just simple sequence of string appending. Unless you have to use it thousands of times and that represents a bottleneck for your application, I'd not waste time make it better, it probably takes a few microseconds, and just upgrading the PHP version would probably make improvements much better than code changes you'd implement.

    If you really have to make it faster, possible solutions are - writing it the function into an extension - APC op code caching (it should make things generally fast when interpreting the code so globally increase the speed) - caching results in memory (only if your application runs the same input many times, that is not probably a common case for a simple algorithm like this one)

    If you want to play with it and try to make it faster, careful, you could alter the logic and introduce a bug. Always use a unit test, or write some test cases before changing it, always a good practice