Pagination is a common feature in web development. Whether it’s displaying article lists, product inventories, or comment data, pagination can significantly improve the user experience and prevent performance issues caused by loading too much content at once. This article will explain how to use the ceil() function in combination with count() in PHP to implement a simple and practical pagination logic.
The core idea of pagination is to divide a large set of data into several "pages," with each page displaying only a portion of the data. For example, if we have 100 records and want to display 10 records per page, we will need 10 pages.
To implement pagination, we need the following key variables:
Total number of records: Obtained using the count() function.
Number of records per page: This can be fixed as a constant or retrieved from the request parameters.
Current page number: Typically obtained from the GET request, such as $_GET['page'].
Total number of pages: Calculated by dividing the total number of records by the number of records per page, and then using ceil() to round up.
Let’s assume we have a set of article data stored in an array:
<?php
$articles = [
'Article 1',
'Article 2',
'Article 3',
'Article 4',
'Article 5',
'Article 6',
'Article 7',
'Article 8',
'Article 9',
'Article 10',
'Article 11',
'Article 12'
];
<p>$perPage = 5; // 5 items per page<br>
$totalItems = count($articles); // Total number of records<br>
$totalPages = ceil($totalItems / $perPage); // Total number of pages</p>
<p>$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;<br>
$page = max(1, min($page, $totalPages)); // Ensure the page number is within a valid range</p>
<p>$offset = ($page - 1) * $perPage; // Starting position for current page's data<br>
$currentItems = array_slice($articles, $offset, $perPage);</p>
<p>foreach ($currentItems as $item) {<br>
echo "<p>$item</p>";<br>
}<br>
?><br>
To allow users to click and navigate to different pages, we need to generate pagination navigation links. Here’s an example:
<?php
echo '<div class="pagination">';
for ($i = 1; $i <= $totalPages; $i++) {
if ($i == $page) {
echo "<strong>$i</strong> ";
} else {
echo "<a href=\"https://m66.net/list.php?page=$i\">$i</a> ";
}
}
echo '</div>';
?>
When users click the links, they will be directed to the corresponding page, and the program will display the data for that page based on the page number.
By using count() to get the total number of records and ceil() to calculate the total number of pages, we can implement a simple and practical pagination logic. Combined with array_slice() and the user’s page number parameter, PHP can efficiently handle the pagination task.
This method works well for pagination of medium to small data sets. For larger data sets, it's recommended to optimize pagination using the database's LIMIT function. Regardless of the method, understanding how ceil() and count() work together is the first step to mastering pagination.