# LUHN10 credit card validation in PHP - example

chris (2006-04-22 09:10:53)
2461 views
0 replies
The luhn algorithm is a simple checksum formula used to check the validity of credit card numbers. It works like this:

First every second digit, beginning with the second to last and moving towards the left is multiplied by 2. If the result of doubling any of those nubmers is is 10 or more, its digits are summed. Thus, a 3 becomes 6 and a 7 becomes 5. Now add all those digits together and divide the result by 10. If the remainder is zero, the original number is valid.

Here is an implementation in PHP:
```function check_cc(\$number) { // first remove any non digits from \$number \$number=preg_replace("/D/","",\$number); \$len = strlen(\$number); for (\$i=0; \$i<\$len; \$i++) { \$q = substr(\$number,\$len-\$i-1,1)*(\$i%2+1); \$r += (\$q%10)+(int)(\$q/10); } return !(\$r%10); } ```
To use this you would do something like:
```if(!check_cc(\$card_number)){ // give an error message }else{ // continue with processing } ```
And that's it.

christo