Generating Luhn Checksums

前端 未结 6 463
挽巷
挽巷 2020-12-28 08:36

There are lots of implementations for validating Luhn checksums but very few for generating them. I\'ve come across this one however in my tests it has revealed to be buggy

6条回答
  •  情歌与酒
    2020-12-28 09:01

    This is a function that could help you, it's short and it works just fine.

    function isLuhnValid($number)
    {
        if (empty($number))
            return false;
    
        $_j = 0;
        $_base = str_split($number);
        $_sum = array_pop($_base);
        while (($_actual = array_pop($_base)) !== null) {
            if ($_j % 2 == 0) {
                $_actual *= 2;
                if ($_actual > 9)
                    $_actual -= 9;
            }
            $_j++;
            $_sum += $_actual;
        }
        return $_sum % 10 === 0;
    }
    

提交回复
热议问题