Menü schliessen
Created: March 25th 2021
Last updated: March 25th 2021
Categories: IT Development,  Php
Author: Miljan Puzovic

PHP Function for generating check digits (for ESR-numbers) for orange Swiss payment slips ("Oranger Einzahlungsschein")

Tags:  algorithm,  check digit,  esr,  PHP
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

This is an algorithm used to create check digits. It's based on recursive usage of Modulo10.

Creating a check digit (algorithm)

Here is a PHP function which can be used to create check digit from any numerical string:

function get_check_digit($input) {
    $input = trim($input);

    if (ctype_digit(strval($input)) === false && is_string() === false)
        return "ERROR: input must be an integer sent as a string. Example: not 1234 or 1234.5 but '1234'!";

    $arrayTable = [0,9,4,6,8,2,7,1,3,5];
    $carry = 0;

    for ($i = 0; $i < strlen($input); $i++) {
        $carry = $arrayTable[($carry + substr($input, $i, 1)) % 10];
    }

    return (10 - $carry) % 10;
}