Skip to content

Instantly share code, notes, and snippets.

@seromenho
Last active August 29, 2015 14:21
Show Gist options
  • Save seromenho/9255a3dc9662f3db1056 to your computer and use it in GitHub Desktop.
Save seromenho/9255a3dc9662f3db1056 to your computer and use it in GitHub Desktop.
PHP Luhn Validator (from Symfony)
<?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