Skip to content

Instantly share code, notes, and snippets.

@riipandi
Created July 2, 2013 04:22
Show Gist options
  • Save riipandi/5906755 to your computer and use it in GitHub Desktop.
Save riipandi/5906755 to your computer and use it in GitHub Desktop.
Sample implementation Damm algorithm in PHP. Generating and Validating. http://en.wikipedia.org/wiki/Damm_algorithm
<?php
/**
* The Damm check digit
* Damm validation & generation code in PHP.
* Damm algorithm is a check digit algorithm that detects all single-digit errors
* and all adjacent transposition errors. Totally anti-symmetric quasigroup.
*
* For more information cf. http://en.wikipedia.org/wiki/Damm_algorithm
*
* @author Wuri Nugrahadi <[email protected]>
*/
if (! function_exists('taq')) {
function taq($digits) {
$taq_table = array(
'0317598642', '7092154863', '4206871359', '1750983426', '6123045978',
'3674209581', '5869720134', '8945362017', '9438617205', '2581436790');
$interim = 0;
foreach (str_split($digits) as $digit) {
if (! preg_match('~\d~', $digit)) {
return FALSE;
}
$interim = substr($taq_table[$interim], $digit, 1);
}
return $interim;
}
}
if (! function_exists('calc_check_digit')) {
function calc_check_digit($digits) {
return $digits.taq($digits);
}
}
if (! function_exists('is_check_digit_valid')) {
function is_check_digit_valid($digits) {
return taq($digits) == 0;
}
}
// Testing
$src = 21081046;
$res = calc_check_digit($src);
echo $res.' : ';
if (is_check_digit_valid($res) == 1)
echo 'Valid';
else
echo 'Invalid';
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment