I've just written a validation routine for a UPC-A, which ensures the check digit matches the given UPC number (according to rules I found on Wiki, mind!).
Below is the code, what do you think?
function valid_upc_a($value)
{
$odd_sum = $even_sum = 0;
if(strlen($value) != 12) return FALSE;
$chars = str_split($value);
for($i=0;$i<11;$i++)
{
$odd_sum += $i%2==0?$chars[$i]:0;
$even_sum += $i%2==1?$chars[$i]:0;
}
$total_sum = $even_sum + $odd_sum*3;
$modulo10 = $total_sum % 10;
$check_digit = 10 - $modulo10;
return (int)$chars[11] === $check_digit;
}
It works for a couple of cases I made up, here it is on CodePad:
http://codepad.viper-7.com/QEqpFX
And the checkdigit derivation algorithm is described here:
http://en.wikipedia.org/wiki/Universal_Product_Code#Check_digits