This article describes how to verify the validity of credit card numbers through the Luhn algorithm in PHP. The example shows how to implement the Luhn algorithm and related application skills in php, which has some reference value, for more information about how to use the Luhn algorithm to verify the validity of credit card numbers, see the example in this article. Share it with you 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) ? 'valid' : 'not valid', '
'; 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;}
Running result
49927398716 is valid49927398717 is not valid1234567812345678 is not valid1234567812345670 is 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 ('20160301', '20160301', '20160301', '20160301') as $ n)
Echo "$ n is", luhn_test ($ n )? 'Valid': 'not valid ',"
\ N ";
The output result is as follows:
49927398716 is valid49927398717 is not valid1234567812345678 is not valid1234567812345670 is valid
I hope this article will help you with php programming.