Skip to content

Instantly share code, notes, and snippets.

@Lutacon
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Lutacon/bba28e94666098d8a2fa to your computer and use it in GitHub Desktop.
Save Lutacon/bba28e94666098d8a2fa to your computer and use it in GitHub Desktop.
Luhn's Algorithm PHP
<?php
/**
* @see http://en.wikipedia.org/wiki/Luhn_algorithm
*/
function is_valid_luhn($number) {
$number = preg_replace("/[^0-9]/", "", $number);
settype($number, 'string');
$sumTable = array(
array(0,1,2,3,4,5,6,7,8,9),
array(0,2,4,6,8,1,3,5,7,9)
);
$sum = 0;
$flip = 0;
for ($i = strlen($number) - 1; $i >= 0; $i--) {
$sum += $sumTable[$flip++ & 1][$number[$i]];
}
return $sum % 10 === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment