Displaying pagination links, maybe with links to first and last page I've been researching if this is possible, but I've drawn a blank, I'm wondering if it's possible to optimize these for and if statements together?

&lt;?php
// calculate total number of pages
$total_pages = ceil($total_rows / $records_per_page);

// range of links to show
$range = 2;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;
?&gt;
    &lt;ul class="pagination margin-zero"&gt;
&lt;?php if ($page&gt;1) : ?&gt;
        &lt;li&gt;
            &lt;a href='&lt;?php echo $page_url; ?&gt;' title='Go to the first page.'&gt;
                First Page
            &lt;/a&gt;
        &lt;/li&gt;
&lt;?php endif; ?&gt;

&lt;?php
for ($x = $initial_num; $x&lt;$condition_limit_num; $x++) :
    if (($x &gt; 0) &amp;&amp; ($x &lt;= $total_pages)) :
        if ($x == $page) : ?&gt;
        &lt;li class='active'&gt;
            &lt;a href="#"&gt;&lt;?php echo $x; ?&gt; &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt;
        &lt;/li&gt;
        &lt;?php else : ?&gt;
        &lt;li&gt;
            &lt;a href='&lt;?php echo $page_url; ?&gt;page=&lt;?php echo $x; ?&gt;'&gt;&lt;?php echo $x; ?&gt;&lt;/a&gt;
        &lt;/li&gt;
        &lt;?php
        endif;
    endif;
endfor;
?&gt;

&lt;?php if ($page&lt;$total_pages) : ?&gt;
        &lt;li&gt;
            &lt;a href='&lt;?php echo $page_url; ?&gt;page=&lt;?php echo $total_pages; ?&gt;' title='Last page is &lt;?php echo $total_pages; ?&gt;'&gt;
                Last Page
            &lt;/a&gt;
        &lt;/li&gt;
&lt;?php endif; ?&gt;

    &lt;/ul&gt;
The main loop code lacks the prior validation. So in the business logic part


verify that $x is positive. if not, make it the least number possible (1 I suppose)
verify that $x is &lt;= $total_pages. Make them equal otherwise
prepare the page numbers in the form of array using $pages = range($initial_num, $condition_limit_num);


So you will have a single loop with a single condition

&lt;?php foreach ($pages as $x): ?&gt;
    &lt;?php if ($x == $page) : ?&gt;
        &lt;li class='active'&gt;
            &lt;a href="#"&gt;&lt;?= $x ?&gt; &lt;span class="sr-only"&gt;(current)&lt;/span&gt;&lt;/a&gt;
        &lt;/li&gt;
    &lt;?php else: ?&gt;
        &lt;li&gt;
            &lt;a href="&lt;?= $page_url ?&gt;page=&lt;?= $x ?&gt;"&gt;&lt;?= $x ?&gt;&lt;/a&gt;
        &lt;/li&gt;
    &lt;?php endif ?&gt;
&lt;?php endfor ?&gt;