When developing a pagination system, calculating the total number of pages is a common requirement. PHP provides a very useful mathematical function, ceil(), which can help us easily solve this problem. This article will explain how to use the ceil() function to accurately calculate the total number of pages in a pagination system with practical examples.
The ceil() function is a built-in PHP mathematical function used to round a number up to the nearest integer. No matter what the decimal part of the number is, ceil() will round it up to the next integer.
For example:
echo ceil(4.1); // Outputs 5
echo ceil(7.99); // Outputs 8
Suppose you have a set of data with a total of 53 records, and you want to display 10 records per page. The total number of pages should be:
53 / 10 = 5.3
We cannot directly treat 5.3 as the total number of pages because the page number must be an integer. If we use regular integer division, we will get only 5 pages, and the last 3 records will be left out. In this case, we need to use the ceil() function to round 5.3 up to 6.
<?php
// Total number of records
$totalRecords = 53;
<p>// Records per page<br>
$perPage = 10;</p>
<p>// Calculate total number of pages, using ceil to round up<br>
$totalPages = ceil($totalRecords / $perPage);</p>
<p>echo "Total number of pages: {$totalPages}"; // Outputs: Total number of pages: 6<br>
?><br>
Suppose you have a page where the URL parameter page is used to switch between pages. Here is an example of a link:
http://m66.net/list.php?page=1
We can combine the total number of pages to generate pagination links:
<?php
$totalRecords = 53;
$perPage = 10;
$totalPages = ceil($totalRecords / $perPage);
<p>echo "<nav><ul>";<br>
for ($i = 1; $i <= $totalPages; $i++) {<br>
echo "<li><a href='<a rel="noopener" target="_new" class="cursor-pointer">http://m66.net/list.php?page={$i}'>Page</a> {$i}</a></li>";<br>
}<br>
echo "</ul></nav>";<br>
?><br>
Now, users can click the links to access different pages of content.
The ceil() function helps us round up, ensuring that the total number of pages is correct.
Total pages = ceil(total records / records per page).
When generating pagination links, you can dynamically create pagination buttons using a loop and the result from ceil().
Using ceil() to calculate the total number of pages is both simple and accurate, making it an essential technique in PHP pagination development.