Code to Validate Check Digits of JAN Codes in PHP

PHP
2023-04-01 11:27 (1 years ago) ytyng
/**
 * 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, ""];
}
Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011