Skip to content

Instantly share code, notes, and snippets.

@nicolopignatelli
Created April 12, 2016 14:20
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 nicolopignatelli/3fa708d2f4ca5f3e5e9c264deab67a9d to your computer and use it in GitHub Desktop.
Save nicolopignatelli/3fa708d2f4ca5f3e5e9c264deab67a9d to your computer and use it in GitHub Desktop.
[PHP] GTIN validator
<?php
function gtinIsValid($gtin) {
$gtin = str_pad(trim($gtin), 14, "0", STR_PAD_LEFT);
$checkSum = 0;
$gtinBody = substr($gtin, 0, strlen($gtin) - 1);
$lastDigit = substr($gtin, -1);
foreach(str_split($gtinBody) as $i => $char) {
if ($i % 2 == 1) {
$checkSum += intval($char);
} else {
$checkSum += (3 * intval($char));
}
}
$checkDigit = (10 - ($checkSum % 10)) % 10;
return $checkDigit === intval($lastDigit);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment