phpmoduluscheck-digit

Validate check digit 11 (mod 11) using PHP


How to validate NHS number using check digit 11 (mod 11) using PHP.

After a long search on the internet trying to find a function that I can use to validate check digit 11 (mod 11) number, I couldn't find so I end up developing one myself and share it here. I hope someone my find it useful.


Solution

  • The code with comments:

    ###### Check Digit 11 Modulus
    function mod11($nhs_no){
        //Get Last Number
        $checkDigit = (int)substr($nhs_no, -1);
        //Get Remaining Numbers
        $numbers = substr($nhs_no, 0, -1);  
        // Sort Numbers Into an Array
        $numbers_array = str_split($numbers);
        //Define the base for the weights
        $base=2;
        // Multiply the weights to the numbers
        $numbers_array_reversed =  array_reverse($numbers_array);
        foreach($numbers_array_reversed as $number){$multiplier[$number.'x'.$base]=(float)$number * $base;$base++;}
        //Get the total sum
        $sum =(float) array_sum($multiplier);
        $modulus = 11;
        // Divide the sum by check digit 11
        $divider = (float)($sum / $modulus);
        // Get the remainder
        $remainder = (int)(($divider - (int)$divider)*$modulus);
        // Check if the remainder is matching with the last check digit
        $results = (int) ($modulus-$remainder);
        // Return true or false 
        return ($results == $checkDigit ? true : false);
    }