note 109457 modified in ref.math by yannick

From: Date: Fri, 20 Jul 2012 14:02:11 +0000
Subject: note 109457 modified in ref.math by yannick
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189320@lists.php.net to get a copy of this message
Another simpler function to check a number with the luhn algorithm :

<?php
function luhn($num){
	if(!$num)
		return false;
	$num = array_reverse(str_split($num));
	$add = 0;
	foreach($num as $k => $v){
		if($k%2)
			$v = $v*2;
		$add += ($v >= 10 ? $v - 9 : $v);
	}
	return ($add%10 == 0);
}
?>

Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer. --was-- Another simpler function to check a number with the luhn algorithm : function luhn($num){ if(!$num) return false; $num = array_reverse(str_split($num)); $add = 0; foreach($num as $k => $v){ if($k%2) $v = $v*2; $add += ($v >= 10 ? $v - 9 : $v); } return ($add%10 == 0); } Don't know if foreach and arrays operations are faster than while and substr, but I feel it clearer. http://php.net/manual/en/ref.math.php

« previous php.notes (#189320) next »