David Ansermot Web Developer / TYPO3 Integrator

26avr/110

PHP – Generate Luhn checksum (for valid account numbers)

Here’s a function to calculate the Luhn checksum of a 15 digits account number (the checksum’ll be the 16th digit) :

  1. public function luhnChecksum($accountNumber) {
  2.                
  3.         // Buffer
  4.         $sum = 0;
  5.        
  6.         // Process each digit
  7.         for ($i = 0; $i < 15; $i++) {
  8.                 $digit = $accountNumber{$i};
  9.                
  10.                 // each 2 digits
  11.                 if ($i % 2 == 0) {
  12.                         $double = $digit * 2;
  13.                        
  14.                         // if over 10, sum of the 2 digits
  15.                         if ($double > 10) {
  16.                                 $double = (string)$double;
  17.                                 $sum += ((int)$double{0} + (int)$double{1});
  18.                         } else {
  19.                                 $sum += $digit;
  20.                         }
  21.                 } else {
  22.                         $sum += $digit;
  23.                 }
  24.         }
  25.        
  26.         // Euclidian division
  27.         $rest = $sum % 10;
  28.        
  29.         // luhn key  
  30.         $key = 10 - $rest;
  31.        
  32.         return $key;
  33. }

Article for teaching purposes.
I can not in any way be held liable for its use

qrCode

Posts that maybe you want to read ::

Commentaires (0) Trackbacks (0)

Aucun commentaire pour l'instant


Leave a comment

(required)

Aucun trackbacks pour l'instant