PHP - Pagination problem

Try to show as materials inputs the number of pages but encountered a problem. If I have many pages they all appear to me. (Page1 pag2 pag4 pag5 page 3 and so on until the last)

I’d like to do something like Back pag1 pag2 pag3 pag4… last page Next

<?php
if ($page+1>1)
{
    echo "<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/" . $page . ".html'>Inapoi</a>";
}
for ($j=1; $j<=$nr_pag; $j++)
{
    echo "
    <a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/".$j.".html'>".$j."</a>";
}
if ($page+1<$nr_pag)
{
    echo "&nbsp;<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/" . ($page + 2) . ".html'>Inainte</a>";
}
?>

Okay, so you know what you want, now think it out :slight_smile:

If I’m not on Page 1, I want a First and Previous link to appear. First should go to Page 1, and Previous should go to the Prior Page.

if ($page != 1)
{
  echo "<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/1.html'>First</a>";
  echo "<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/".($page - 1).".html'>Prev</a>";
}

Now for the next part, I only want to show 4 pages (instead of all of them)

for ($j=1; $j<=$nr_pag && $j <= 4; $j++) // added && $j <= 4
{
    echo "
    <a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/".$j.".html'>".$j."</a>";    
}

Finally the Next and Last links: I want to show the Next/Last links only when I’m not on the last page.

if ($page != $nr_pag)
{
  echo "<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/".($page + 1).".html'>Next</a>";
  echo "<a class='letter_box' style='margin-bottom:2px; margin-top:2px;' href='/muzica-online/".$nr_pag.".html'>Last</a>";
}