Luhn algorithm in PHP
20051226 8:53 by javierAs I mentioned before, the Luhn algorithm is used to validate some interesting numbers, most notably GSM IMEIs and credit card numbers. Here’s another implementation I wrote, this time in PHP.
function luhn($str) {
$odd = !strlen($str)%2;
$sum = 0;
for($i=0;$i<strlen($str);++$i) {
$n=0+$str[$i];
$odd=!$odd;
if($odd) {
$sum+=$n;
} else {
$x=2*$n;
$sum+=$x>9?$x-9:$x;
}
}
return(($sum%10)==0);
}
$odd = !strlen($str)%2;
$sum = 0;
for($i=0;$i<strlen($str);++$i) {
$n=0+$str[$i];
$odd=!$odd;
if($odd) {
$sum+=$n;
} else {
$x=2*$n;
$sum+=$x>9?$x-9:$x;
}
}
return(($sum%10)==0);
}
(Download)





















February 24th, 2006 at 11:14
I think you’ve got a little error there; you’ve got your even/odd reversed:
function luhn($str) {
$odd = !strlen($str)%2;
$sum = 0;
for($i=0;$i9?$x-9:$x;
}
$odd=!$odd;
}
return(($sum%10)==0);
}
February 24th, 2006 at 12:34
*heheh* Well, there’s a double negative in there, and I admit that it is kind of confusing at first glance. Be assured that the implementation works as intended. You might want to take a look to the Demo for the Luhn Algorithm in PHP to check out some numbers and see that it does work.
January 24th, 2008 at 12:28
heres a better one:
function luhn($s) {
$sum=0;
$res=preg_match(”/[0-9]{14,16}/”,str_replace(”-”,”",$s),$s);
if ($res==0) { return false; }
$s=$s[0];
$i=strlen($s);
while ($i–>=0) {
$sum+=(($i%2)==0)?(($s[$i]*2)>9)?(($s[$i]*2)-9):($s[$i]*2):$s[$i];
}
return (($sum%10)==0);
}
August 11th, 2008 at 17:30
Limpc,
You’re making an assumption that the card will be 14-16 characters long. This assumption is incorrect.
http://en.wikipedia.org/wiki/Credit_card_number
August 13th, 2008 at 11:04
What the Hell, $str? $str%2 is a methematical operation, the complete operations are mathematical, the parameter has to be named $int, all creditcards use integer values.
Before you can start anything, please validate the data.
Strip spaces convert to int or use explizit typehinding.
Since php5 return exceptions or since php4 raise or return an error objekt so the programmer will receive informations about what is making trouble with this “number”.
And what will this do? $n = 0+$str[$i]; ???
Beside of this little Semantik mistakes i will thank you alot for this, it has be avoked alot of work for me, thanks very much.