How to divide an array of 90 elements into 20 on each page, in PHP?

Asked

Viewed 39 times

-3

A query via mysqli (in PHP) returns me 90 lines in an array. How do I print a maximum of 20 lines on each page ? I developed it as follows, but it’s still too grotesque:

Can someone help me perfect that code ?

<?php
$linhas = 92;
$i = 1;
while ($i <= $linhas) :
    echo $i . "<br>";
    $i++;
    while ($i % 20 == 0) :?>
        <div style="page-break-before: always"> <?= $i ?> </div> <?php
        $i++;
    endwhile;
endwhile;
?>

2 answers

0

Put in query LIMIT 20, so SELECT * FROM table LIMIT 20

  • 1

    Even better: LIMIT 0, 20 to the front page, LIMIT 20, 20 for the second, and so on.

  • Good idea, I hadn’t thought of that.

-2

if you want to paginate an array follows an ex of how to do using array_slice

<?php
$lista=array();
for($i=1;$i<=90;$i++){
    $lista[]=$i;    
}


function paginate($lista,$pagina=0,$numporpag=20){
    if($pagina==0){ $pagina = 1; }
    $total = count($lista); 
    $paginas = ceil($total/$numporpag); 
    $ini = ($numporpag * $pagina) - $numporpag;
    
    $fim = ($numporpag * $pagina - 1);  
    return array_slice($lista, $ini, $fim);
    
}


print_r(paginate($lista,1));

print_r(paginate($lista,2));

print_r(paginate($lista,3));

print_r(paginate($lista,4));

print_r(paginate($lista,5));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.