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实现该算法(第一种):
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位银行卡卡号。