Php pagination with links range. Need help adjusting the loop
<p>I need this kind of pagination 
<a href="https://i.stack.imgur.com/cxlkf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cxlkf.jpg" alt="enter image description here"></a></p>

<p>with a small change </p>

<p>the pagination should never show more than 5 buttons/links ( not counting next/prev ) and if I am somewhere in mid of pagination it should show </p>

<p>1 ... 5 6 7 ... 20 </p>

<p>or </p>

<p>1... 9 10 11 ... 20</p>

<p>if on last page </p>

<p>1... 17 18 19 20 </p>

<p>I started  with this </p>

<pre><code>function pagination (){
    // prev link

    $html ='';
    $numpages = 20;
    $current_page = 1;
    $dotshow = true;

    if ($numpages != 1) {
        $html .='&lt;span&gt;&lt;i class="fa fa-angle-left"&gt;&lt;/i&gt;&lt;/span&gt;';// prev


        for($i=1; $i &lt;= $numpages; $i++){


            if ($i == 1 || $i == $numpages ||  ($i &gt;= $current_page - 3 &amp;&amp;  $i &lt;= $current_page + 3) ) {
                  $dotshow = true;
                  if ($i != $current_page){

                    $html .='&lt;a class="pagination-link" href="#linkhere"&gt;';
                    $html .='&lt;span&gt; '.$i.'&lt;/span&gt;';
                    $html .='&lt;/a&gt;'; 

                  }else{
                    $html .='&lt;span class="current"&gt;';
                    $html .='&lt;span&gt; '.$i.'&lt;/span&gt;';
                    $html .='&lt;/span&gt;';            

                  }
               }else if ( $dotshow ){

                   $dotshow = false;
                    $html .='&lt;span class="dots"&gt;';
                    $html .='&lt;span&gt; ... &lt;/span&gt;';
                    $html .='&lt;/span&gt;';  
            }

        }
        $html .='&lt;span&gt;&lt;i class="fa fa-angle-right"&gt;&lt;/i&gt;&lt;/span&gt;';// next
    }
    if($html !=''){
        return $html;
    }

}
</code></pre>

<p>on first and last I get this </p>

<p><a href="https://i.stack.imgur.com/DPgSt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DPgSt.jpg" alt="enter image description here"></a>
<a href="https://i.stack.imgur.com/y5H4c.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y5H4c.jpg" alt="enter image description here"></a></p>

<p>but on my page 5 it shows this and number of links increases because of the wrong current , total , limit calc. </p>

<p><a href="https://i.stack.imgur.com/8RKoF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8RKoF.jpg" alt="enter image description here"></a></p>

<p>any help is appreciated!</p>