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

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, especially in retail or retail outlets around the world, with the exception of America of the North where the UPC barcode is used.

     

link

I needed a function to calculate the DV of EAN-13 mentioned in the above passage. At the time I searched everywhere and did not find anything about it.

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

    
asked by anonymous 29.06.2018 / 14:24

2 answers

4

Here's 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 at IDEONE .

It has been adapted from this post: link - maybe I'll edit later with an original of mine, I did not like this $weightflag . I would probably use a $i%2 and invert the loop (with care to keep from right to left).

    
29.06.2018 / 14:50
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);

?>
    
29.06.2018 / 21:21