Home > Backend Development > PHP Tutorial > PHP uses Luhn algorithm to verify whether the credit card number is valid

PHP uses Luhn algorithm to verify whether the credit card number is valid

墨辰丷
Release: 2023-03-31 17:46:02
Original
1418 people have browsed it

This article mainly introduces the PHP implementation of checking whether the credit card number is valid through the Luhn algorithm. It analyzes the implementation of the Luhn algorithm in PHP and related application techniques with examples. It has certain reference value. Friends in need can refer to it

The example in this article describes how PHP implements the Luhn algorithm to verify whether a credit card number is valid. The specific implementation method is as follows:

$numbers = "49927398716 49927398717 1234567812345678 1234567812345670";
foreach (split(' ', $numbers) as $n)
  echo "$n is ", luhnTest($n) ? &#39;valid&#39; : &#39;not valid&#39;, &#39;</br>&#39;;
 
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

Running result

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

The following is a more concise code:

The code is as follows:

function luhn_test($num) {
    $str = &#39;&#39;;
    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(&#39;49927398716&#39;,&#39;49927398717&#39;,&#39;1234567812345678&#39;,&#39;1234567812345670&#39;) as $n)
echo "$n is ", luhn_test($n) ? &#39;valid&#39; : &#39;not valid&#39;, "</br>\n";
Copy after login

The output result is as follows

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

Summary: The above is the entire content of this article, I hope it will be helpful to everyone's study.

Related recommendations:

php method to subtract two arrays

php method to traverse and delete files using a recursive function

php associative array sorting method

The above is the detailed content of PHP uses Luhn algorithm to verify whether the credit card number is valid. For more information, please follow other related articles on the PHP Chinese website!

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