I originally added this to Wikipedia’s Luhn algorithm page but one of their editors deemed there to be too many language implementations, and so they scrubbed it.

I’m posting it here for other PHP programmers, this might save you a few minutes work.

function validLuhn($number) { for ($sum = 0, $i = strlen($number) - 1; $i >= 0; $i--) { $digit = (int) $number[$i]; $sum += (($i % 2) === 0) ? array_sum(str_split($digit * 2)) : $digit; } return (($sum % 10) === 0); }

In case the code above isn’t clear (it’s deliberately succinct). Lets pick the code apart.

Take the card number 4242 4242 4242 4242, this passes a Luhn check.

- Parse card number (PAN) digits from right to left, so starts at the end and works backwards.

`2424 2424 2424 2424`

- Starting with the second digit, double every second digit (D).

`2828 2828 2828 2828`

- As we work backwards through the PAN, keep a sum (S) of the digits.

`2+8+2+8+2+8+2+8+2+8+2+8+2+8+2+8 = 80`

- If D is 10 or greater, sum the two numbers (our example PAN doesn’t exceed 8).

`6x2 = 12. 1+2 = 3`

- If the sum S is cleanly divisible by 10, with no remainder the PAN passes the Luhn check.

`80 % 10 = 0`

**Update**

I needed a Javascript version:

function luhnCheck(pan) { for (var i = pan.length - 1, sum = 0, digit; i >= 0; i -= 1) { digit = parseInt(pan[i], 10); sum += (i % 2 === 0) ? eval(String(digit * 2).split('').join('+')) : digit; } return (sum % 10) === 0; }Tweet

## comments

No comments for this post.