Home > Backend Development > PHP Tutorial > PHP implements the Luhn algorithm to verify whether the credit card number is valid, luhn algorithm_PHP tutorial

PHP implements the Luhn algorithm to verify whether the credit card number is valid, luhn algorithm_PHP tutorial

WBOY
Release: 2016-07-13 10:01:07
Original
1460 people have browsed it

PHP implements the Luhn algorithm to verify whether the credit card number is valid, luhn algorithm

This article describes the example of PHP implementing the Luhn algorithm to verify whether the credit card number is valid. Share it with everyone for your reference. The specific implementation method is as follows:

$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

Run results

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

Here is a more concise code:
Copy code The code is as follows: 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";

The output results are as follows

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

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/972647.htmlTechArticlePHP implements the Luhn algorithm to verify whether the credit card number is valid. The luhn algorithm is an example. This article describes the PHP implementation of the Luhn algorithm. How to verify whether the credit card number is valid. Share it with everyone...
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