How can the code be refactored to improve readability and maintainability?
The code can be refactored by breaking down the logic into smaller, more manageable functions and using meaningful variable names. This will improve readability and maintainability by making the code easier to understand and update in the future.
function calculateTotalPrice($items) {
$totalPrice = 0;
foreach ($items as $item) {
$totalPrice += $item['price'] * $item['quantity'];
}
return $totalPrice;
}
function generateInvoice($customerName, $items) {
$totalPrice = calculateTotalPrice($items);
$invoice = "Invoice for: $customerName\n";
$invoice .= "Items:\n";
foreach ($items as $item) {
$invoice .= "- {$item['name']} x {$item['quantity']} = {$item['price']}\n";
}
$invoice .= "Total Price: $totalPrice";
return $invoice;
}
$customerName = "John Doe";
$items = [
['name' => 'Item 1', 'price' => 10, 'quantity' => 2],
['name' => 'Item 2', 'price' => 20, 'quantity' => 1]
];
$invoice = generateInvoice($customerName, $items);
echo $invoice;
Related Questions
- How can PHP developers optimize their code to prevent SQL injection vulnerabilities when inserting data into a MySQL database?
- How can the use of $_REQUEST be improved in the PHP code provided?
- What potential pitfalls should be considered when implementing password encryption in PHP for an existing user base?