public
Last active

Luhn's algorithm in php

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13
<?php
function is_valid_luhn($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++ & 0x1][$number[$i]];
}
return $sum % 10 === 0;
}

<?php
function is_valid_nums($s){
$s = strrev(preg_replace('/[^\d]/','',$s));
$sum = 0;
for ($i = 0,$j=strlen($s); $i < $j; $i++) {
if ($i % 2 ==0) {
$val = $s[$i];
}else {
$val = $s[$i]*2;
if ($val >9) {
$val -=9;
}
$sum += $val;
}
return(($sum % 10) == 0);
}
if (! is_valid_nums($_POST['nums'])) {
echo 'the num is invalid.';
}
}
?>

Please be aware that this functions will only work if the passed argument is a string, else it will fail.
For more info read:

http://lamp-ios.com/?p=256

It has to do with 1 thing:
1. Your platform (32 or 64 bit)

Be aware of this

Here is a simple implementation:

/**
 * @see http://en.wikipedia.org/wiki/Luhn_algorithm
 */
private function checksum ($card_number) {
    $card_number_checksum = '';

    foreach (str_split(strrev((string) $card_number)) as $i => $d) {
        $card_number_checksum .= $i %2 !== 0 ? $d * 2 : $d;
    }

    return array_sum(str_split($card_number_checksum)) % 10 === 0;
}

You can simply typecast whatever input you have into a string before applying it to the function or you could incorporate a step to first typecast your arguments into strings.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.