public
Created

PHP Function to Validate EANs

  • Download Gist
ean_check.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
<?php
 
/*
0346745008178
Should fail - checksum should be 9
 
5060096384137
Should pass
 
5020650002112
Should pass
*/
 
$eans = array(
'5020650002112',
'5060096384137',
'0346745008178'
);
 
foreach ($eans as $ean) {
var_dump(ean_check($ean));
}
 
function ean_check($ean) {
$ean = strrev($ean);
// Split number into checksum and number
$checksum = substr($ean, 0, 1);
$number = substr($ean, 1);
$total = 0;
for ($i = 0, $max = strlen($number); $i < $max; $i++) {
if (($i % 2) == 0) {
$total += ($number[$i] * 3);
} else {
$total += $number[$i];
}
}
$mod = ($total % 10);
$calculated_checksum = (10 - $mod);
if ($calculated_checksum == $checksum) {
return true;
} else {
return false;
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.