In what ways can the PHP code be refactored to follow better coding standards and improve readability?
Issue: The PHP code is difficult to read and does not follow coding standards, making it hard to maintain and understand. To improve readability and adhere to better coding practices, we can break down the code into smaller functions, use meaningful variable names, and properly indent the code. Refactored PHP code:
<?php
// Original code
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
$cartItems = [
['name' => 'Item 1', 'price' => 10, 'quantity' => 2],
['name' => 'Item 2', 'price' => 20, 'quantity' => 1],
];
$total = calculateTotal($cartItems);
echo 'Total: $' . $total;
// Refactored code
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
$total += $item['price'] * $item['quantity'];
}
return $total;
}
$cartItems = [
['name' => 'Item 1', 'price' => 10, 'quantity' => 2],
['name' => 'Item 2', 'price' => 20, 'quantity' => 1],
];
$total = calculateTotal($cartItems);
echo 'Total: $' . $total;
Related Questions
- How can one ensure clean and efficient code when manipulating strings and arrays in PHP?
- How can PHP and SQL work together to ensure that data is properly sorted and displayed in an HTML table based on specific criteria?
- What are the best practices for implementing a pagination function in PHP to ensure user-friendly navigation?