Luhn algorithm

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux