How can the code be optimized to ensure accurate validation of customer numbers using the Modulo10-Verfahren in PHP?

To optimize the code for accurate validation of customer numbers using the Modulo10-Verfahren in PHP, we can streamline the algorithm and error handling. One way to do this is by creating a function that specifically handles the validation process, making the code more modular and easier to maintain.

function validateCustomerNumber($customerNumber) {
    $customerNumber = str_replace(' ', '', $customerNumber); // Remove any spaces
    $customerNumber = str_split($customerNumber); // Convert the customer number into an array of digits

    $sum = 0;
    $parity = count($customerNumber) % 2;

    foreach ($customerNumber as $key => $digit) {
        $digit = (int)$digit;
        if ($key % 2 === $parity) {
            $digit *= 2;
            if ($digit > 9) {
                $digit -= 9;
            }
        }
        $sum += $digit;
    }

    return $sum % 10 === 0;
}

// Example usage
$customerNumber = "1234 5678 9012 3456";
if (validateCustomerNumber($customerNumber)) {
    echo "Customer number is valid.";
} else {
    echo "Customer number is invalid.";
}