This article mainly introduces the PHP implementation through the LUHN algorithm to verify the validity of the credit card number, an example of the implementation of PHP Luhn algorithm and related application skills, with a certain reference value, the need for friends can refer to the next
In this paper, the method of verifying the validity of the credit card number by using the Luhn algorithm is described in PHP. The implementation method is as follows:
$numbers = "49927398716 49927398717 1234567812345678 1234567812345670"; foreach (Split (", $numbers) as $n) echo" $n I S ", 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% 10 = = 0;}
Run results
49927398716 is valid49927398717 are not valid1234567812345678 are not valid1234567812345670 are valid
The following is a more concise 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 ', ' </br>\n ';
The output is as follows
49927398716 is valid49927398717 are not valid1234567812345678 are not valid1234567812345670 are valid
Summary : The above is the entire content of this article, I hope to be able to help you learn.