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

WBOY
Release: 2016-05-31 11:45:34
Original
809 people have browsed it

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

$numbers = "49927398716 49927398717 1234567812345678 1234567812345670";
foreach (split(' ', $numbers) as $n)
  echo "$n is ", luhnTest($n) &#63; '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;
}
Copy after login

运行结果

49927398716 is valid
49927398717 is not valid
1234567812345678 is not valid
1234567812345670 is valid
Copy after login
Copy after login

下面是一个更为简洁的代码:

代码如下:

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
Copy after login
Copy after login

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

Related labels:
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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template