Skip to content

Instantly share code, notes, and snippets.

@guerrato
Created May 10, 2018 19:39
Show Gist options
  • Save guerrato/8044db612c10d30702396af4aec1b154 to your computer and use it in GitHub Desktop.
Save guerrato/8044db612c10d30702396af4aec1b154 to your computer and use it in GitHub Desktop.
This file contains a PHP code to generate a checksum based in Luhn Algorithm.
/**
* This file contains a PHP code to generate a checksum based in Luhn Algorithm.
* To learn more about Luhn algorithm: https://en.wikipedia.org/wiki/Luhn_algorithm
* To validate the generated code: https://www.dcode.fr/luhn-algorithm
*
* @param string $code
* @return int
*
* Example: $code = '7992739871'
* function returning: 3
*/
public function luhnChecksum($code)
{
$digits = array_reverse(str_split($code));
foreach ($digits as $index => $value) {
if($index % 2 === 0) {
$digits[$index] *= 2;
if($digits[$index] > 9) {
$digits[$index] -= 9;
}
}
}
$mod = array_sum($digits) % 10;
return $mod > 0 ? 10 - $mod : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment