Created
May 10, 2018 19:39
-
-
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 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
/** | |
* 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