pastebin - collaborative debugging tool
kpaste.net RSS


Luhn algorithm
Posted by Admin on Sat 22nd Jan 2011 21:16
raw | new post

  1. <?php
  2. $num = "49927398716";
  3.  
  4. $double = false;
  5. $ret = "";
  6.  
  7. for ($i = strlen($num) - 1; $i >= 0; $i--) {
  8.         $ret .= ($double ? $num[$i] * 2 : $num[$i]);
  9.         $double = !$double;
  10. }
  11. $ret = strrev($ret);
  12. $sum = 0;
  13.  
  14. for ($i = 0; $i < strlen($ret); $i++) {
  15.         $sum += $ret[$i];
  16. }
  17. echo "\$ret = $ret\n";
  18. echo "\$sum = $sum\n";
  19.  
  20. if ($sum % 10) {
  21.         echo "Invalid\n";
  22. } else {
  23.         echo "Valid\n";
  24. }

Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:

To highlight particular lines, prefix each line with {%HIGHLIGHT}





All content is user-submitted.
The administrators of this site (kpaste.net) are not responsible for their content.
Abuse reports should be emailed to us at