Skip to content


Luhn 10 algorithm for credit card check

The luhn_check() function is a small PHP function which checks whether a number is a valid based on the Luhn algoritm.
This function may be used to check for valid credit card numbers, however additional checks may be desired, such as
card prefix and length checks.

<pre><code>&lt;?

function luhn_check($number) {

// Strip any non-digits (useful for credit card numbers with spaces and hyphens)
$number=preg_replace(‘/\D/’, ”, $number);

// Set the string length and parity
$number_length=strlen($number);
$parity=$number_length % 2;

// Loop through each digit and do the maths
$total=0;
for ($i=0; $i&lt;$number_length; $i++) {
$digit=$number[$i];
// Multiply alternate digits by two
if ($i % 2 == $parity) {
$digit*=2;
// If the sum is two digits, add them together (in effect)
if ($digit &gt; 9) {
$digit-=9;
}
}
// Total up the digits
$total+=$digit;
}

// If the total mod 10 equals 0, the number is valid
return ($total % 10 == 0) ? TRUE : FALSE;

}

?&gt;</code></pre>

Posted in PHP, Techie.

Tagged with , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

Spam protection by WP Captcha-Free



Copy Protected by Chetan's WP-CopyProtect.