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
- Are there best practices for managing URL structure in PHP projects to avoid overly complex and unreadable URLs?
- When working with PHP classes and methods, how can the data returned from a function be efficiently utilized in a separate PHP file for rendering HTML content?
- What are some common methods in PHP for storing data from a form in a database?