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
Related posts
Posting XML with PHP using Zend Framework HTTP Client
Using Vue.js Webpack Dev Server Proxy for Social Provider Authentication with Django + Python Social Auth
Remote Debugging via Reverse Port Forwarding with PHP SSH
PHP with Mac Brew: dlopen(/usr/local/opt/php56-intl/intl.so, 9): Library not loaded: /usr/local/opt/icu4c/lib/libicuuc.57.dylib
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.
We look forward to discussing your development needs.