How can proper code indentation and commenting improve the readability and maintainability of PHP scripts, especially when dealing with nested structures?
Proper code indentation and commenting can improve the readability and maintainability of PHP scripts by making the code structure clearer and easier to follow, especially when dealing with nested structures. Indentation helps visually represent the hierarchy of code blocks, while comments provide explanations for complex logic or functionality.
<?php
// Example of properly indented and commented PHP code with nested structures
function calculateTotal($items) {
$total = 0;
foreach ($items as $item) {
// Calculate subtotal for each item
$subtotal = $item['price'] * $item['quantity'];
// Add subtotal to total
$total += $subtotal;
}
// Apply discount if total exceeds $100
if ($total > 100) {
$total *= 0.9; // 10% discount
}
return $total;
}
$cart = [
['name' => 'Product A', 'price' => 20, 'quantity' => 2],
['name' => 'Product B', 'price' => 30, 'quantity' => 1]
];
$total = calculateTotal($cart);
echo "Total: $" . $total;
?>
Related Questions
- What is the recommended best practice for including files in PHP to avoid path issues?
- How can understanding the flow of data between PHP and JavaScript help in troubleshooting issues like the "continue must be inside loop" error message?
- What are the system requirements for running a PHP forum with moderate traffic on a self-hosted Apache server?