Luhn算法会通过校验码对一串数字进行验证,校验码通常会被加到这串数字的末尾处,从而得到一个完整的身份识别码。
我们以数字“7992739871”为例,计算其校验位:
另一种方法是:
使用PHP实现该算法(第一种):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 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实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 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位银行卡卡号。
原文:http://www.cnblogs.com/-mrl/p/5242084.html