Created
September 3, 2014 23:05
-
-
Save kivlor/f2169d9455a0fd6d3f9d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function encode_ean13($number) | |
{ | |
// String it and make it the right length | |
$digits = (string)$number; | |
$digits = strlen($digits) < 12 ? str_pad($digits, 12, '0', STR_PAD_LEFT) : $digits; | |
// Add the values of the digits in the even-numbered positions: 2, 4, 6, etc. | |
$even_sum = $digits{1} + $digits{3} + $digits{5} + $digits{7} + $digits{9} + $digits{11}; | |
// Multiply this result by 3. | |
$even_sum_three = $even_sum * 3; | |
// Add the values of the digits in the odd-numbered positions: 1, 3, 5, etc. | |
$odd_sum = $digits{0} + $digits{2} + $digits{4} + $digits{6} + $digits{8} + $digits{10}; | |
// Sum the results of steps 2 and 3. | |
$total_sum = $even_sum_three + $odd_sum; | |
// The check character is the smallest number which, when added to the result in step 4, produces a multiple of 10. | |
$next_ten = (ceil($total_sum/10))*10; | |
$check_digit = $next_ten - $total_sum; | |
return $digits.$check_digit; | |
} | |
// EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment