PHP snippet to calculate reference number for Finnish invoices

(Finnish summary: PHP aliohjelma, jolla voi laskea laskun viitenumeron laskun numerosta.)

I’m not sure how many countries are using so called 7-3-1 method to generate reference numbers for Invoices, but here in Finland it’s a common practise. Looks like that Estonians are using the same.

Anyway, I needed to create a PHP code to generate reference numbers. I found nice information here: https://wiki.xmldation.com/support/fk/finnish_reference_number

I though that someone else may one day need same functionality, so here’s the snippet. It’s a PHP function that takes invoice number and adds a check digit at the end. And that’s, there’s your reference number. Have fun 🙂

   private function calcInvoiceRefNum($invoice_num) {
        $digits = str_split($invoice_num);
        $method = [7,3,1];
        $mi = 0; // $method array index
        $sum = 0;
        
        $index = count($digits);
        
        // Walk through all digits in reverse order and sum up
        while ($index) {
            --$index;
            
            $sum += $digits[$index] * $method[$mi];
            
            $mi++;
            if ($mi > 2) $mi = 0;
        }
        
        // Find the next zero ending number from $sum
        $nearest_10 = ceil($sum / 10) * 10;
        
        // Add the checksum to the end of the invoice number
        $last_digit = $nearest_10 - $sum;
        if ($last_digit == 10)
            $last_digit = 0;
        
        return $invoice_num.$last_digit;
    }

1 thought on “PHP snippet to calculate reference number for Finnish invoices”

Comments are closed.