How can the PHP code provided be optimized to improve readability and maintainability?
The PHP code can be optimized for readability and maintainability by breaking down the long if-else statement into smaller, more manageable parts using functions or switch statements. This will make the code easier to understand and modify in the future.
function getDiscount($userType, $totalAmount) {
switch ($userType) {
case 'regular':
return calculateRegularDiscount($totalAmount);
break;
case 'premium':
return calculatePremiumDiscount($totalAmount);
break;
default:
return 0;
}
}
function calculateRegularDiscount($totalAmount) {
// Calculate discount logic for regular users
return $totalAmount * 0.1;
}
function calculatePremiumDiscount($totalAmount) {
// Calculate discount logic for premium users
return $totalAmount * 0.2;
}
$userType = 'regular';
$totalAmount = 100;
$discount = getDiscount($userType, $totalAmount);
echo "Discount for $userType user is: $discount";