HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

UPC-A validation

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
upcvalidationstackoverflow

Problem

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 Wikipedia).

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

Solution

Good function, only when $modulo10 is 0 it should not be substracted from 10, so it would be something like this:

function valid_upc_a($value) {
    $upc = strval($value);

    if(!isset($upc[11])) {
        return FALSE;
    }

    $odd_sum = $even_sum = 0;

    for($i = 0; $i  0)
        $check_digit = 10 - $modulo10;
    else 
       $check_digit = 0;        

    return $upc[11] == $check_digit;
}

Code Snippets

function valid_upc_a($value) {
    $upc = strval($value);

    if(!isset($upc[11])) {
        return FALSE;
    }

    $odd_sum = $even_sum = 0;

    for($i = 0; $i < 11; ++$i) {
        if ($i % 2) {
            $even_sum += $upc[$i];
        } else {
            $odd_sum += $upc[$i];
        }
    }

    $total_sum = $even_sum + $odd_sum * 3;
    $modulo10 = $total_sum % 10;

    if ($modulo10 > 0)
        $check_digit = 10 - $modulo10;
    else 
       $check_digit = 0;        

    return $upc[11] == $check_digit;
}

Context

StackExchange Code Review Q#19438, answer score: 3

Revisions (0)

No revisions yet.