Our blog

 

EAN13 Barcode Check Digit with PHP

EAN13 is a barcode format. It consists of 12 numbers which you will generally have a range assigned to you. The 13th digit is called the check digit and is formulated by loooking at the other 12 digits. The purpose of the check digit is to ensure that the number is being read correctly as if any of the numbers do not match up, the check digit will not validate.

If you need to create check digits in PHP, here is my handy function:

PHP:
  1. function ean13_check_digit($digits){
  2. //first change digits to a string so that we can access individual numbers
  3. $digits =(string)$digits;
  4. // 1. Add the values of the digits in the even-numbered positions: 2, 4, 6, etc.
  5. $even_sum = $digits{1} + $digits{3} + $digits{5} + $digits{7} + $digits{9} + $digits{11};
  6. // 2. Multiply this result by 3.
  7. $even_sum_three = $even_sum * 3;
  8. // 3. Add the values of the digits in the odd-numbered positions: 1, 3, 5, etc.
  9. $odd_sum = $digits{0} + $digits{2} + $digits{4} + $digits{6} + $digits{8} + $digits{10};
  10. // 4. Sum the results of steps 2 and 3.
  11. $total_sum = $even_sum_three + $odd_sum;
  12. // 5. The check character is the smallest number which, when added to the result in step 4,  produces a multiple of 10.
  13. $next_ten = (ceil($total_sum/10))*10;
  14. $check_digit = $next_ten - $total_sum;
  15. return $digits . $check_digit;
  16. }

Other Barcode Related Resources:

http://phpclasses.fonant.com/browse/package/3643.html

http://thinkabdul.com/2007/01/04/barcoder-freeware-ean-13-barcode-reader-for-java-j2me-mobiles/

More Reading:

5 Comments

Rémi
October 14th, 2010

There is a better way that works with EAN13 and EAN8:

PHP:
  1. function get_ean_checkdigit($barcode){
  2.         $sum = 0;
  3.         for($i=(strlen($barcode));$i>0;$i--){
  4.                 $sum += (($i % 2) * 2 + 1 ) * substr($barcode,$i-1,1);
  5.         }
  6.         return (10 - ($sum % 10));
  7. }

--
Rémi

 

admin
October 14th, 2010

nice - added syntax highlighting to make it more readable

 

Frank
January 28th, 2011

Function added by Rémi is not correct, it gives out the wrong result.
However, original function by admin is correct.
Thanks a lot.

 

jerry
July 31st, 2011

Function added by ADMIN is not correct - you need to multiple odd number by 3 not even

$next_ten = (ceil(((3*$odd_sum)+$even_sum)/10))*10

 

GioMBG
January 30th, 2012

ONLY THANKS!

 

 

Leave a Reply