Skip to content

Instantly share code, notes, and snippets.

@defiant
Created March 8, 2013 21:50
Show Gist options
  • Save defiant/5120182 to your computer and use it in GitHub Desktop.
Save defiant/5120182 to your computer and use it in GitHub Desktop.
Checks a number and returns true if it validates according to Luhn Algorithm
/**
* Valid Luhn Number Checker
*/
class Luhn
{
static public function valid($num)
{
$odd = 0;
$even = 0;
// reverse string
$str = strrev($num);
$strArr = str_split($str);
foreach ($strArr as $k => $n) {
if (self::_isOdd($k)) {
// odd
$odd += $n;
}else{
// even
$n = $n * 2;
$even += self::_strSum($n);
}
}
return ($odd + $even) % 10 ? false : true;
}
protected static function _isOdd($num)
{
return (bool) !($num % 2);
}
protected static function _strSum($num)
{
if(strlen($num) > 1){
return (substr($num, 0, 1) + substr($num, 1));
}else{
return $num;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment