Demo for Luhn algorithm in PHP

If you have a number that adheres to the Luhn algorithm for validation, you may check it easily with this short PHP snippet.

<?php
function luhn($str) {
        $odd = !strlen($str)%2;
        $sum = 0;
        for($i=0;$i<strlen($str);++$i) {
            $n=0+$str&#91;$i&#93;;
            $odd=!$odd;
            if($odd) {
                $sum+=$n;
            } else {
                $x=2*$n;
                $sum+=$x>9?$x-9:$x;
            }
        }
        return(($sum%10)==0);
}
$num = $_GET['number'];
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Online Luhn algorithm test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<?php if($num) { ?>
<?php   if(luhn($num)) { ?>
<div style="background:#ddffdd;border:1px solid #004400;">
<?=htmlspecialchars($num)?> is valid
</div>
<?php   } else { ?>
<div style="background:#ffdddd;border:1px solid #880000;">
<?=htmlspecialchars($num)?> is NOT valid
</div>
<?php   } ?>
<?php } ?>
<form action="luhn.php" method="GET">
<div>
Number: <input type="text" name="number" value="<?=urlencode($num)?>" size="40"/>
<input type="button" name="btSend" value="Check"/>
</div>
</form>
</body>

(Download)
You may test this script at https://javier.rodriguez.org.mx/code/luhn-test.php.
Please consider that this is a demo, so please do not use this to check credit card numbers unless you send me an expiry date. CCV2 has taken over as the preferred method for credit card number validation anyway.

Luhn algorithm in PHP

As 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&#91;$i&#93;;
			$odd=!$odd;
			if($odd) {
				$sum+=$n;
			} else {
				$x=2*$n;
				$sum+=$x>9?$x-9:$x;
			}
		}
		return(($sum%10)==0);
	}

(Download)