Skip to content

Instantly share code, notes, and snippets.

@andronex
Forked from DaveChild/ean_check.php
Created June 28, 2020 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andronex/86f6d81b7825660e489d3f027b51435f to your computer and use it in GitHub Desktop.
Save andronex/86f6d81b7825660e489d3f027b51435f 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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment