Checking if a variable is set
if (isset($_GET["page_num"]) && $_GET["page_num"] >= 2): ?>
Here you check if $_GET["page_num"]
is set before using it, which is correct. However, you don't do so in any of the later tests. Consider starting with something the code block with something like
$currentPage = isset($_GET['page_num']) ? $_GET['page_num'] : 1;
Now you can just use $currentPage
instead. And it will always be set. It defaults to 1
, as that is the normal pagination behavior (no selected page means the first page).
I also changed the double quotes to single quotes. In PHP, double quotes means that a string is open to variable interpolation. You aren't using variable interpolation, so you might as well use single quotes instead.
Later you can change the original line of code to
if ($currentPage > 1) {
?>
Note that I also moved the closing ?>
to its own line. This makes it much easier to tell when you switch from code to HTML.
I also switched from the non-standard :
notation. Very little PHP code is written that way. The only time that I've actually seen it is in WordPress templates.
And I switched from >= 2
to > 1
because 2
is not a significant number here. What you are saying is that you don't want allow the back link on the first page, only on pages after the first. This translates to > 1
more directly.
Separating PHP and HTML
I'd tend to write this as
<?php
$currentPage = isset($_GET['page_num']) ? $_GET['page_num'] : 1;
?>
<div class="row">
<div class="twelve columns tac">
<?php
echo getPaginationLinks($currentPage, $totalPages);
?>
</div>
</div>
and define getPaginationLinks
in a separate file with most of the original block. The getPaginationLinks
function would build and return a string.
Note that I put the <?php>
and ?>
on separate lines and at the beginning of each line. This makes it easier to tell when you are switch from HTML to PHP code.
Don't switch context for no reason
You have
for ($i = 1; $i <= $totalPages; $i++): ?>
<?php if ($i == $_GET["page_num"]) : ?>
You could just as well write this
for ($i = 1; $i <= $totalPages; $i++):
if ($i == $_GET["page_num"]) :
?>
Then the compiler isn't switching from PHP context to HTML context just to print out some meaningless whitespace. As @tim said, in this case it would be even better to build the string in PHP code rather than mixing PHP and HTML. In other situations this construct would be more acceptable. But there's still no point in switching out of PHP context unless you want to display something before you switch back into it.