Function to calculate the Checker Digit of an EAN-13 code

Asked

Viewed 1,168 times

1

EAN-13 is a barcode in the EAN standard defined by GS1, adapted in more than one hundred GS1 member organizations, for the identification of items, mainly at retail or retail outlets around the world, with the exception of North America where the UPC barcode is used.

https://en.wikipedia.org/wiki/International_Article_Number

I needed a function to calculate the EAN-13 DV, mentioned in the above section. At the time I looked everywhere and found nothing about it.

After getting a solution, I came to share here on the site, follows in the field of answers.

2 answers

4

Follows an alternative:

function generateEANdigit($code)
{
  $weightflag = true;
  $sum = 0;
  for ($i = strlen($code) - 1; $i >= 0; $i--) {
    $sum += (int)$code[$i] * ($weightflag?3:1);
    $weightflag = !$weightflag;
  }
  return (10 - ($sum % 10)) % 10;
}

See working on IDEONE.

Was adapted from this post: https://stackoverflow.com/a/19890444/916193 - maybe I edit later with an original of mine, I didn’t like this $weightflag. I’d probably wear one $i%2 and flip the loop (with the care to keep from right to left).

  • 1

    Alternatively, you can add $code = strval($code); in the first line of the function. Demonstration by passing the value as integer: https://ideone.com/PN9EHN

1

<?php

function digito($cod)
{
   $cnt=1; $arr = str_split($cod); foreach($arr as $k => $v){ if($cnt % 2 == 0) { $par = ($par+$v); }else{ $impar = ($impar+$v); } $cnt++; } $par   = ($par*3);
   $res = (floor(($par+$impar)/10)); $res = ($res+1) * 10 - ($par+$impar);                      
   if(floor($res) % 10 == 0){ $res = '0'; } 
   return $cod.$res;
}

// Usabilidade: Ao Chamar a função com os 12 algarismos retorna já com o dígito.
echo IncluiDigito(789100031550);

?>
  • Here is a place to test if the result is correct: https://www.gs1.org/services/check-digit-calculator#gtin

Browser other questions tagged

You are not signed in. Login or sign up in order to post.