How can the PHP code be improved for better readability and maintainability?
Issue: The PHP code can be improved for better readability and maintainability by organizing it into smaller functions with clear names and responsibilities. This will make the code easier to understand, debug, and modify in the future.
// Original code
function calculateTotalPrice($items) {
$total = 0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
// Improved code
function calculateTotalPrice($items) {
$total = 0;
foreach ($items as $item) {
$total += calculateItemTotal($item['price'], $item['quantity']);
}
return $total;
}
function calculateItemTotal($price, $quantity) {
return $price * $quantity;
}
Related Questions
- Are there any security concerns related to directly using user input in SQL queries, as shown in the code example?
- What are the best practices for debugging PHP scripts that involve executing external programs?
- What PHP functions or methods can be used to convert and compare IPv4 and IPv6 addresses effectively for database storage and retrieval purposes?