What are some best practices for dynamically generating page navigation links in PHP?
When dynamically generating page navigation links in PHP, it's important to consider factors such as the total number of pages, the current page number, and the desired number of links to display. One common approach is to use a loop to generate the links based on these factors, along with conditional logic to handle edge cases such as the first and last pages.
<?php
$totalPages = 10;
$currentPage = 5;
$linksToShow = 5;
echo '<div class="pagination">';
for ($i = max(1, $currentPage - floor($linksToShow / 2)); $i <= min($totalPages, $currentPage + floor($linksToShow / 2)); $i++) {
echo '<a href="?page=' . $i . '"';
if ($i == $currentPage) {
echo ' class="active"';
}
echo '>' . $i . '</a>';
}
echo '</div>';
?>