How can loops and conditional statements be effectively used in PHP to streamline code for generating page numbers?
To streamline code for generating page numbers in PHP, loops can be used to iterate through a range of page numbers, while conditional statements can be used to determine which page numbers to display based on the current page and the total number of pages.
<?php
$current_page = 5;
$total_pages = 10;
echo "<ul>";
for ($i = 1; $i <= $total_pages; $i++) {
if ($i == $current_page) {
echo "<li><strong>$i</strong></li>";
} else {
echo "<li><a href='page.php?page=$i'>$i</a></li>";
}
}
echo "</ul>";
?>
Related Questions
- What are some best practices for incorporating template systems into PHP forums?
- How can the stateless nature of HTTP pose challenges when trying to limit access to a PHP page to one user at a time?
- What potential security risks are associated with displaying MySQL query results directly on a webpage in PHP?