How can the code provided be improved for better readability and efficiency in PHP?
The code can be improved for better readability and efficiency by using more descriptive variable names, breaking down complex logic into smaller functions, and removing unnecessary repetition.
// Improved code with better variable names and logic separation
function calculateTotalPrice($items) {
$totalPrice = 0;
foreach ($items as $item) {
$price = $item['price'];
$quantity = $item['quantity'];
$totalPrice += $price * $quantity;
}
return $totalPrice;
}
$items = [
['name' => 'Item 1', 'price' => 10, 'quantity' => 2],
['name' => 'Item 2', 'price' => 20, 'quantity' => 1]
];
$totalPrice = calculateTotalPrice($items);
echo "Total Price: $totalPrice";
Related Questions
- What are common reasons for "Access denied" errors when connecting to a MySQL database in PHP?
- In the provided PHP code, what improvements can be made to ensure proper session data storage and retrieval?
- What are the security implications of using PHP scripts for handling user interactions across different domains?