Home > php教程 > php手册 > PHP实现通过Luhn算法校验信用卡卡号是否有效

PHP实现通过Luhn算法校验信用卡卡号是否有效

WBOY
Release: 2016-06-06 20:06:03
Original
941 people have browsed it

这篇文章主要介绍了PHP实现通过Luhn算法校验信用卡卡号是否有效,实例分析了php实现Luhn算法及相关应用技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了PHP实现通过Luhn算法校验信用卡卡号是否有效的方法。分享给大家供大家参考。具体实现方法如下:

$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; }

运行结果

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', "\n";

输出结果如下

49927398716 is valid 49927398717 is not valid 1234567812345678 is not valid 1234567812345670 is valid

希望本文所述对大家的php程序设计有所帮助。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template