How can the code snippet provided be improved for better readability and maintainability?
The code snippet can be improved for better readability and maintainability by breaking down the logic into smaller, more descriptive functions and using meaningful variable names. This will make the code easier to understand and maintain in the future.
function calculateTotalPrice($products) {
$totalPrice = 0;
foreach ($products as $product) {
$totalPrice += $product['price'] * $product['quantity'];
}
return $totalPrice;
}
$products = [
['name' => 'Product A', 'price' => 10, 'quantity' => 2],
['name' => 'Product B', 'price' => 20, 'quantity' => 1],
['name' => 'Product C', 'price' => 15, 'quantity' => 3]
];
$totalPrice = calculateTotalPrice($products);
echo "Total Price: $" . $totalPrice;
Keywords
Related Questions
- What is the significance of nl2br function in PHP and how can it be used in this context?
- What are the recommended methods for handling and updating serialized data structures like the one shown in the forum thread in PHP?
- How can PHP handle HTTP requests efficiently when checking the validity of multiple links?