Skip to content

Instantly share code, notes, and snippets.

@DaveChild
Created November 23, 2011 10:45
Show Gist options
  • Save DaveChild/1388411 to your computer and use it in GitHub Desktop.
Save DaveChild/1388411 to your computer and use it in GitHub Desktop.
PHP Function to Validate EANs
<?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;
}
}
@IDKWare
Copy link

IDKWare commented May 31, 2021

I think is KO with this : 8854740061270

Try with Pavelbier's fork: https://gist.github.com/pavelbier/4a2b42b8498ba62cbaf24230223a86a9

$calculated_checksum it's different.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment