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
- How can different versions of PHP and Apache impact the passing of variables through URLs in PHP scripts?
- What are the best practices for defining and using OAuth consumer key and secret in PHP when working with the Xing API?
- What ethical considerations should developers keep in mind when accessing and verifying user data from external sources in PHP applications?