2010/1/5 Angus Mann <angusmann@xxxxxxxxx>: > Hi all. Perhaps a lazy request, but does anybody have some cut-n-paste code to calculate a Luhn check-digit? > > It's a check-digit often added to the end of things like credit card or account numbers to make detecting typo's a bit easier. > > I found lots of code to validate a number once the check-digit is applied, but nothing to calculate the digit in the first place. > > Thanks in advance ! > Angus > > Modified version found at http://blog.planzero.org/2009/08/luhn-modulus-implementation-php/ <?php /* Luhn algorithm number checker - (c) 2005-2008 - planzero.org * * This code has been released into the public domain, however please * * give credit to the original author where possible. */ function luhn_check($number) { // If the total mod 10 equals 0, the number is valid return (luhn_process($number) % 10 == 0) ? TRUE : FALSE; } function luhn_process($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<$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 > 9) { $digit-=9; } } // Total up the digits $total+=$digit; } return $total; } function luhn_checkdigit($number) { return 10 - (luhn_process($number . '0') % 20); } echo '49927398716 is ', (luhn_check('49927398716') ? 'Valid' : 'Invalid'), PHP_EOL; echo 'The check digit for 4992739871 is ', luhn_checkdigit('4992739871'), PHP_EOL; ?> outputs ... 49927398716 is Valid The check digit for 4992739871 is 6 -- ----- Richard Quadling "Standing on the shoulders of some very clever giants!" EE : http://www.experts-exchange.com/M_248814.html Zend Certified Engineer : http://zend.com/zce.php?c=ZEND002498&r=213474731 ZOPA : http://uk.zopa.com/member/RQuadling -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php