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

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

WBOY
WBOYOriginal
2016-06-13 09:09:591465browse

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

本文实例讲述了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;
}

运行结果

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程序设计有所帮助。

Statement:
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