PHP uses the Luhn algorithm to verify whether the credit card number is valid. PHP uses the Luhn algorithm to verify whether the credit card number is valid. the luhn algorithm in this article describes how PHP uses the Luhn algorithm to verify whether the credit card number is valid. The Luhn algorithm is used to verify whether the credit card number is valid.
This example describes how to use the Luhn algorithm to verify the validity of credit card numbers in PHP. 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.
Example: This article describes how PHP uses the Luhn algorithm to verify the validity of credit card numbers. Share it with you...