PHP uses the Luhn algorithm to verify whether the credit card number is valid. PHP uses the Luhn algorithm to verify whether a credit card number is valid. This article mainly describes how PHP uses the Luhn algorithm to verify whether a credit card number is valid, the example analyzes the Luhn algorithm implemented by php and the Luhn algorithm used by PHP to verify whether the credit card number is valid.
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, see
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$ 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
?
1 2 3 4 |
Is valid 49927398716 49927398717 is not valid 1234567812345678 is not valid Is valid 1234567812345670 |
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:
?
1 2 3 4 |
Is valid 49927398716 49927398717 is not valid 1234567812345678 is not valid Is valid 1234567812345670 |
I hope this article will help you with php programming.
This article describes how to use the Luhn algorithm to verify the validity of credit card numbers in PHP. The example shows how to use php to implement the Luhn algorithm and...