user6893344
user6893344

Reputation:

How to add a pagination for foreach loop data in PHP

I have set of data displaying inside my foreach loop, i want to show only 10 at a time and display a paging for others. pls advice

        foreach ($files as $file) {
            ?>
              <div class="name">
                    <img src="<?php echo $file->getIconPath() ?>" alt="" />
                    <div class="info">
                        <h2 class="filename"><?php echo $file->filename ?></h2>
                        <div class="path">
                            <?php echo $file->filetype ?>
                        </div>
                    </div>
 <?php }?>

Upvotes: 2

Views: 2604

Answers (1)

Saeed M.
Saeed M.

Reputation: 2361

array_slice is the function you need to split an array. This is how a pagination works in arrays.

$allFiles = globe("*");
$page = isset($_GET['page']) ? $_GET['page'] : 0;
$count = count($allFiles);
$perPage = 5;
$numberOfPages = ceil($count / $perPage);
$offset = $page * $perPage;
$files = array_slice($allFiles, $offset, $perPage);
foreach($files as $file){
   //
}

Upvotes: 5

Related Questions