本文实例讲述了PHP实现通过Luhn算法校验信用卡卡号是否有效的方法。分享给大家供大家参考。具体实现方法如下:
PHP;">
$numbers = "49927398716 49927398717 1234567812345678 1234567812345670";
foreach (split(' ',$numbers) as $n)
echo "$n is ",luhnTest($n) ? 'valid' : 'not valid','';
function luhnTest($num) {
$len = strlen($num);
for ($i = $len-1; $i >= 0; $i--) {
$ord = ord($num[$i]);
if (($len - 1) & $i) {
$sum += $ord;
} else {
$sum += $ord / 5 + (2 * $ord) % 10;
}
}
return $sum % 10 == 0;
}
运行结果
PHP;">
49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid
下面是一个更为简洁的代码:
代码如下:
$c ) $str .= ($i % 2 ? $c * 2 : $c );
return array_sum( str_split($str) ) % 10 == 0;
}
foreach (array('49927398716','49927398717','1234567812345678','1234567812345670') as $n)
echo "$n is ",luhn_test($n) ? 'valid' : 'not valid',"\n";
输出结果如下
PHP;">
49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid
希望本文所述对大家的PHP程序设计有所帮助。
原文链接:https://www.f2er.com/php/22308.html