Code to Validate Check Digits of JAN Codes in PHP
PHP
2023-04-01 02:27 (3 years ago)
/**
* Validate the JAN check digit and return [success?, message]
*/
function validate_jan($jan): array
{
$match = preg_match('|^(\d{12})(\d)$|', $jan, $matches);
if (!$match) {
return [false, 'Digit count error'];
}
$chars = str_split($matches[1]);
$odd_total = 0;
$even_total = 0;
foreach ($chars as $i => $v) {
if ($i % 2 == 0) {
// Starting from 0, so 0 is an odd digit
$odd_total += $v;
} else {
$even_total += $v;
}
}
$total = $even_total * 3 + $odd_total;
$digit = (10 - ($total % 10)) % 10;
if ($matches[2] != $digit) {
return [false, "Check digit mismatch. The correct digit is {$digit}"];
}
return [true, ""];
}
Please rate this article (No signup or login required)
Currently unrated
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.