Created
March 8, 2013 21:50
-
-
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
This file contains hidden or 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
/** | |
* 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