Last active
April 17, 2019 08:38
-
-
Save francescozanoni/1aa532ff8e796bcd5c36f34501f4f31b to your computer and use it in GitHub Desktop.
[PHP] IBAN check digits calculator (WITHOUT bcmath EXTENSION)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Calculate IBAN check digits (WITHOUT bcmath EXTENSION). | |
* | |
* Inspired by https://github.com/arhs/iban.js/blob/master/iban.js | |
* | |
* @param string $countryCode ISO 3166 2-letter country code, e.g. "FR" | |
* @param string $bban IBAN without country code and without check digits, e.g. "20041010050500013M02606" | |
* | |
* @return string e.g. "14" | |
*/ | |
function calculateCheckDigits($countryCode, $bban) | |
{ | |
$temp = $bban . $countryCode . '00'; | |
$temp = strtoupper($temp); | |
$temp = str_split($temp); | |
$temp = array_map(function($n) { | |
$code = ord($n); | |
if ($code >= ord('A') && $code <= ord('Z')) { | |
return $code - ord('A') + 10; | |
} else { | |
return $n; | |
} | |
}, $temp); | |
$temp = implode('', $temp); | |
$remainder = $temp; | |
$block = null; | |
while (strlen($remainder) > 2) { | |
$block = substr($remainder, 0, 9); | |
$remainder = (intval($block, 10) % 97) . substr($remainder, strlen($block)); | |
} | |
$checkDigits = intval($remainder, 10) % 97; | |
$checkDigits = 98 - $checkDigits; | |
$checkDigitsAsAtring = sprintf('%02d', $checkDigits); | |
return $checkDigitsAsAtring; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment