时间:2021-07-01 10:21:17 帮助过:30人阅读
具体实现方法如下:
- $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 判断IP是否合法正则表达式代码
php 判断访客是否为搜索引擎蜘蛛的函数代码
PHP 判断客户端是IOS还是Android
以上就是PHP校验信用卡号实例的详细内容,更多请关注Gxl网其它相关文章!