Luhn algorithm for validating credit cards


Posted in: algorithms, php | Save to del.icio.us | 9 Jul 2008



The Luhn algorithm also known as the “modulus 10″ or “mod 10″ algorithm, is a checksum formula which can be used to validate credit card numbers. Developed in the 1950’s by IBM scientist Hans Peter Luhn and described in U.S. Patent 2,950,048. A PHP implementation is shown below.

 
function LuhnCheck($strDigits)
{
    $sum = 0;
    $alt = false;
    for($i = strlen($strDigits) - 1; $i >= 0; $i--) 
    {
        if($alt)
        {
           $temp = $strDigits[$i];
           $temp *= 2;
           $strDigits[$i] = ($temp > 9) ? $temp = $temp - 9 : $temp;
        }
        $sum += $strDigits[$i];
        $alt = !$alt;
    }
    return $sum % 10 == 0;
}





1 Response

1

SneakyWho_am_i

May 21st, 2009 at 2:36 am

Looks pretty well optimized too. Great post!
Will like to play with this function and read through it more slowly later on when I have some free time :-)

Comments are disabled for this post, but if you have spotted an error, feel free to contact me.

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

  • Users Online

    • 9 Users Online
    • 8 Guests, 1 Bot
  • RECENT COMMENTS

    ON TWITTER