Skip to content

@DaveChild /ean_check.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.