Generating Luhn Checksums

前端 未结 6 460
挽巷
挽巷 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:20

    your php is buggy, it leads into an infinite loop. This is the working version that I'm using, modified from your code

    function Luhn($number) {

    $stack = 0;
    $number = str_split(strrev($number));
    
    foreach ($number as $key => $value)
    {
        if ($key % 2 == 0)
        {
            $value = array_sum(str_split($value * 2));
        }
        $stack += $value;
    }
    $stack %= 10;
    
    if ($stack != 0)
    {
        $stack -= 10;     $stack = abs($stack);
    }
    
    
    $number = implode('', array_reverse($number));
    $number = $number . strval($stack);
    
    return $number; 
    

    }

    Create a php and run in your localhost Luhn(xxxxxxxx) to confirm.

提交回复
热议问题