本文實例講述了PHP實現通過Luhn算法校驗信用卡卡號是否有效的方法。分享給大家供大家參考。具體實現方法如下:
$numbers = "49927398716 49927398717 1234567812345678 1234567812345670"; foreach (split(' ', $numbers) as $n) echo "$n is ", luhnTest($n) ? 'valid' : 'not valid', '</br>'; 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; }
運行結果
49927398716 is valid 49927398717 is not valid 1234567812345678 is not valid 1234567812345670 is valid
下面是一個更為簡潔的代碼:
復制代碼 代碼如下:function luhn_test($num) {
$str = '';
foreach( array_reverse( str_split( $num ) ) as $i => $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', "</br>\n";
輸出結果如下
49927398716 is valid 49927398717 is not valid 1234567812345678 is not valid 1234567812345670 is valid
希望本文所述對大家的php程序設計有所幫助。