I am creating functions in my code to clean it up, one of them is for working out the offset for pagination.
The function is
function pageOffSet($page, $count, $resultsPerPage) {
// WORK OUT HIGHEST PAGE NUMBER
$pageCount = ceil($count / $resultsPerPage);
// IF GET PAGE VARIABLE IS HIGHER THAN MAX PAGE POSSIBLE
if (isset($page) && $page > $pageCount) {
$page = $pageCount;
// IF VALID GET PAGE VARIABLE
} elseif (isset($page) && is_numeric($page) && $page > 1) {
$page = $page;
// IF PAGE GET VARIABLE NOT SET
} else {
$page = 1;
}
// OFFSET FOR POST RESULTS
$offSet = ($page - 1) * $resultsPerPage;
return array('offSet' => $offSet, 'resultsPerPage' => $resultsPerPage);
}
And I call it like,
$page = pageOffSet($_GET['page'], $count, 15);
Except $_GET['page'] may be set or unset? I check inside the function to see if it is set or not, but is it ok to do this? I get no errors but I just want to check?
An error will not occur, but a warning will probably be generated, depending on your error reporting settings. However, a better approach may be using an default argument:
Then to check if
$pageis there, use:Or to check if it’s not there, use:
This way, you can use the first two arguments without needing to provide the last; or you can provide all three. To use
$page, check if it isNULLor not and use it accordingly.