Last active
August 29, 2015 14:21
-
-
Save seromenho/9255a3dc9662f3db1056 to your computer and use it in GitHub Desktop.
PHP Luhn Validator (from Symfony)
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 value using the LUHN Algorithm. | |
* @param string $value Value to validate. EG: Credit card number | |
* @return bool | |
*/ | |
function isLuhn($value) | |
{ | |
if (!is_string($value) || !ctype_digit($value)) { | |
return false; | |
} | |
$checkSum = 0; | |
$length = strlen($value); | |
for ($i = $length - 1; $i >= 0; $i -= 2) { | |
$checkSum += $value{$i}; | |
} | |
for ($i = $length - 2; $i >= 0; $i -= 2) { | |
$checkSum += array_sum(str_split($value{$i} * 2)); | |
} | |
if (0 === $checkSum || 0 !== $checkSum % 10) { | |
return false; | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment