Displaying pagination links, maybe with links to first and last page
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;