Question

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?

Was it helpful?

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

OTHER TIPS

You might have a look at this repo:

https://github.com/jschaedl/Iban

On your part is to add the rules for croatia. After that you should be able to use it for your country.

Greetz

To microoptimize, the substr has O(n) time complexity, so your loop has O(n2). To avoid it, use str_split and access the chars of the generated array by index.

Then, to make it more elegant, the for loop can be replaced with array_reduce.

Also, generally avoid string concatenation in loop, it has O(n2) time and memory complexity. IBAN is short and PHP is not run on microcomputers, so it is not a issue here. But if you ever worked with longer strings, generate an array and then implode it*.

And, of course, if you are consistent with spacing around = and after for/if, it is also more elegant ;-)


* In Javascript I once tried to generate HTML table of Hangul alphabet by iterative string concatenation. It crashed the browser consuming 1GB+ memory.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top