Generating UPC check digit


Posted in: algorithms, php | Save to del.icio.us | 20 Sep 2009



The following small code generates check digit for UPC-A codes. You can use it for example to generate random UPC-A codes.

Check digit calculation

The check digit is calculated as follows:
1. Add the digits in the odd-numbered positions together and multiply by three.
2. Add the digits in the even-numbered positions to the above result.
3. Find the result modulo 10 (i.e. the remainder when the result is divided by 10).
4. If the result is not zero, subtract the result from ten.

Code

<?php
 
 
function generate_upc_checkdigit($upc_code)
{
    $odd_total  = 0;
    $even_total = 0;
 
    for($i=0; $i<11; $i++)
    {
        if((($i+1)%2) == 0) {
            /* Sum even digits */
            $even_total += $upc_code[$i];
        } else {
            /* Sum odd digits */
            $odd_total += $upc_code[$i];
        }
    }
 
    $sum = (3 * $odd_total) + $even_total;
 
    /* Get the remainder MOD 10*/
    $check_digit = $sum % 10;
 
    /* If the result is not zero, subtract the result from ten. */
    return ($check_digit > 0) ? 10 - $check_digit : $check_digit;
}
 
echo generate_upc_checkdigit("72438451112");
 
?>





1 Response

1

outsource software development

September 22nd, 2009 at 10:51 pm

Good program i have implemented it and it works fine.

Leave a Reply

Get latest updates by E-mail

About this blog

This site is a digital habitat of Sameer, a freelance web developer working from Pune.More

  • Users Online

    • 12 Users Online
    • 12 Guests
  • RECENT COMMENTS

    ON TWITTER