Last active
December 16, 2015 04:14
-
-
Save sergio-bobillier/c619bfdc77e41cb4e926 to your computer and use it in GitHub Desktop.
Clean implementation of the Luhn algorithm in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** Validates a credit card number using the Luhn algorithm. | |
* http://en.wikipedia.org/wiki/Luhn_algorithm | |
* | |
* @param string $card_number The card number (without spaces, dots, or other | |
* special characters, only the numbers). | |
* | |
* @return boolean True if the number is valid, false otherwise. | |
* | |
*/ | |
public function is_card_number_valid($card_number) | |
{ | |
$digits = str_split($card_number); | |
$n = count($digits); | |
$sum = 0; | |
$dbl = false; | |
for($i = $n - 1; $i >= 0; $i--) | |
{ | |
$digit = $digits[$i]; | |
if($dbl) | |
{ | |
$digit = $digit * 2; | |
if($digit >= 10) $digit -= 9; | |
} | |
$dbl = !$dbl; | |
$sum += $digit; | |
} | |
if($sum % 10 == 0) | |
return true; | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A lot of Luhn Algorithm implementations on PHP around the net are unnecessarily complex, they do operations over the array keys or strange, inefficient ways of adding the numbers of the partial products. Here is a simple, and cleaner implementation.
Tested with credit card numbers generated with: http://www.getcreditcardnumbers.com/