In the given PHP code snippet, what improvements could be made to make the discount calculation more efficient and maintainable?
The given code snippet calculates discounts based on various conditions using nested if statements, which can become complex and hard to maintain as more conditions are added. To improve efficiency and maintainability, we can use a more structured approach like using switch statements or creating a separate function for discount calculation based on specific criteria.
// Improved discount calculation using switch statements
$discount = 0;
$subtotal = 100;
switch ($userType) {
case 'regular':
$discount = 0.1;
break;
case 'premium':
$discount = 0.2;
break;
default:
$discount = 0;
}
if ($subtotal > 100) {
$discount += 0.05;
}
$total = $subtotal - ($subtotal * $discount);
echo "Total after discount: $total";
Related Questions
- In the context of PHP cURL requests, what are the differences between passing parameters as a urlencoded string versus an array, and how does it impact API authentication?
- How can PHP beginners utilize arrays to efficiently manage translations of text in their scripts?
- In what scenarios should the mysql_fetch_assoc() function be used in PHP for retrieving data from a database?