How can pagination be implemented in PHP to display search results in a user-friendly manner?
When displaying search results in PHP, pagination can be implemented to break up the results into multiple pages, making it more user-friendly for the viewer to navigate through the data. This can be achieved by limiting the number of results displayed per page and providing navigation links to move between pages.
// Assuming $searchResults is an array containing the search results
$resultsPerPage = 10;
$totalResults = count($searchResults);
$totalPages = ceil($totalResults / $resultsPerPage);
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$start = ($page - 1) * $resultsPerPage;
$end = $start + $resultsPerPage;
$paginatedResults = array_slice($searchResults, $start, $resultsPerPage);
foreach ($paginatedResults as $result) {
// Display each search result
}
// Display pagination links
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='search.php?page=$i'>$i</a> ";
}