Luhn algorithm
| From: | itoctopus | Date: | Sat, 24 Mar 2007 18:51:03 +0000 |
| Subject: | Luhn algorithm | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-251292@lists.php.net to get a copy of this message | ||
Here's the Luhn algorithm in PHP. The Luhn algorithm is mainly used to check
if a credit/debit card number is valid or not.
Please tell me if there's a bug somewhere, I've tested the thing heavily and
it's working like a charm.
/*
*@function check_luhn
*@desc This function checks if a card number follows the Luhn algorithm
*@param string $strCreditCardNumber The card number (maybe AMEX, Diner's
Club, Discover, JCB, Maestro, MasterCard, Solo, Switch, Visa, and Visa
Electron)
*@return boolean TRUE if the card follows the Luhn algorith, false if not
*@usage check_lun('4123456789012345')
*/
function check_luhn($strCardNumber){
//first convert the credit card number to an array of digits
$arrCardDigits = array();
for ($i = 0; $i < strlen($strCardNumber); $i++)
$arrCardDigits[$i] = (int)$strCardNumber[$i];
//now start the algorithm
$sum = 0;
$alt = false;
for($i = count($arrCardDigits) - 1; $i >= 0; $i--){
if($alt){
$arrCardDigits[$i] *= 2;
if($arrCardDigits[$i] > 9)
$arrCardDigits[$i] -= 9;
}
$sum += $arrCardDigits[$i];
$alt = !$alt;
}
return $sum % 10 == 0;
}
--
itoctopus - http://www.itoctopus.com