Is the approach of calculating the check digit by subtracting from 10 and handling cases where the result is 10 or negative numbers correct?

The issue with calculating the check digit by subtracting from 10 is that it may result in negative numbers or a check digit of 10. To solve this issue, we can modify the calculation to handle these cases by adding conditional statements to ensure the check digit is always a single digit between 0 and 9.

function calculateCheckDigit($number) {
    $sum = 0;
    $multiplier = 1;
    
    for ($i = strlen($number) - 1; $i >= 0; $i--) {
        $digit = (int)$number[$i];
        $product = $digit * $multiplier;
        
        $sum += $product;
        $multiplier = ($multiplier == 2) ? 1 : 2;
    }
    
    $checkDigit = 10 - ($sum % 10);
    
    if ($checkDigit == 10) {
        $checkDigit = 0;
    }
    
    return $checkDigit;
}

// Example usage
$number = "123456";
$checkDigit = calculateCheckDigit($number);
echo "Check Digit: " . $checkDigit;