Created
November 23, 2011 10:45
-
-
Save DaveChild/1388411 to your computer and use it in GitHub Desktop.
PHP Function to Validate EANs
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 | |
/* | |
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
Try with Pavelbier's fork: https://gist.github.com/pavelbier/4a2b42b8498ba62cbaf24230223a86a9
$calculated_checksum
it's different.