Luhn算法會通過校驗碼對一串數字進行驗證,校驗碼通常會被加到這串數字的末尾處,從而得到一個完整的身份識別碼。
我們以數字“7992739871”爲例,計算其校驗位:
- 從校驗位開始,從右往左,偶數位乘2(例如,7*2=14),然後將兩位數字的個位與十位相加(例如,10:1+0=1,14:1+4=5);
- 把得到的數字加在一起(本例中得到67);
- 將數字的和取模10(本例中得到7),再用10去減(本例中得到3),得到校驗位。
另一種方法是:
- 從校驗位開始,從右往左,偶數位乘2,然後將兩位數字的個位與十位相加;
- 計算所有數字的和(67);
- 乘以9(603);
- 取其個位數字(3),得到校驗位。
- 使用PHP實現該算法(第一種):
/**
* PHP實現Luhn算法(方式一)
* @author:http://nonfu.me
*/
$no = '7432810010473523';
$arr_no = str_split($no);
$last_n = $arr_no[count($arr_no)-1];
krsort($arr_no);
$i = 1;
$total = 0;
foreach ($arr_no as $n){
if($i%2==0){
$ix = $n*2;
if($ix>=10){
$nx = 1 + ($ix % 10);
$total += $nx;
}else{
$total += $ix;
}
}else{
$total += $n;
}
$i++;
}
$total -= $last_n;
$x = 10 - ($total % 10);
if($x == $last_n){
echo '符合Luhn算法';
}
另一種算法的PHP實現:
/**
* PHP實現Luhn算法(方式二)
* @author:http://nonfu.me
*/
$no = '6228480402564890018';
$arr_no = str_split($no);
$last_n = $arr_no[count($arr_no)-1];
krsort($arr_no);
$i = 1;
$total = 0;
foreach ($arr_no as $n){
if($i%2==0){
$ix = $n*2;
if($ix>=10){
$nx = 1 + ($ix % 10);
$total += $nx;
}else{
$total += $ix;
}
}else{
$total += $n;
}
$i++;
}
$total -= $last_n;
$total *= 9;
if($last_n == ($total%10)){
echo '符合Luhn算法';
}
經檢測,能夠校驗16位或19位銀行卡卡號。