The example of this article tells the PHP implementation through the LUHN algorithm to verify the validity of the credit card card number method. Share to everyone for your reference. The implementation methods are as follows:
$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)%
}
}
return $sum% = 0;
}
Run results
49927398716 is valid 49927398717 are not valid 1234567812345678 are not valid
1234567812345670 are
valid
Here's a more concise code:
Copy Code code 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 ', ' </br>\n ';
The output is as follows
49927398716 is valid 49927398717 are not valid 1234567812345678 are not valid
1234567812345670 are
valid
I hope this article will help you with your PHP program design.