Skip to content

Instantly share code, notes, and snippets.

@francescozanoni
Last active August 14, 2018 05:36
Show Gist options
  • Save francescozanoni/6489e64d22e54acaa55dd09773ca458d to your computer and use it in GitHub Desktop.
Save francescozanoni/6489e64d22e54acaa55dd09773ca458d to your computer and use it in GitHub Desktop.
[PHP] Compute Italy/San Marino's BBAN checksum (CIN - Control Internal Number)

A BBAN example is X0542811101000000123456, whereas

  • X is the checksum (CIN)
  • 05428 is the bank code (ABI)
  • 11101 is the branch code (CAB)
  • 000000123456 is the account number

The only official source describing the checksum computation algorithm, found so far, is http://www.cnb.cz/cs/platebni_styk/iban/download/TR201.pdf , at page 81.

/**
 * Compute Italian BBAN checksum
 *
 * @param string $bbanWC BBAN without checksum
 *
 * @return string
 */
function getChecksum($bbanWC)
{

  $digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
  $letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '.', ' '];
  $lengthOfBbanWC = 22;
  $divisor = 26;
  $evenList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28];
  $oddList = [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23, 27, 28, 26];

  // Character value computation
  $sum = 0;

  for ($k = 0; $k < $lengthOfBbanWC; $k++) {

    $i = array_search($bbanWC[$k], $digits);
    if ($i === false) {
      $i = array_search($bbanWC[$k], $letters);
    }

    // In case of wrong characters, an unallowed checksum value is returned
    if ($i === false) {
      return '';
    }

    $sum += (($k % 2) == 0 ? $oddList[$i] : $evenList[$i]);

  }

  return $letters[$sum % $divisor];

}

This is a quick-and-dirty PHP translation of Visual Basic code available at http://community.visual-basic.it/lucianob/archive/2004/12/26/2464.aspx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment