1

I have text file and i want to show page number for displaying in page
for example my text file have 100 lines , i can show them with array in table , every line in one row like below :
this is my text file example:

mycontent-54564-yoursdsd
condsadtent-5544564-fyfdfdsd
....
//convert into array
$lines = file('myfile.txt');
//count number of lines
$numbers=count($lines);
//show every line in a row of table :
foreach ($lines as $line) {
      $line=explode("-", $line);
      echo "<tr>";
      echo "<td>$line[0]</td>";
      echo "<td>$line[1]</td>";
      echo "<td>$line[2]</td>";
      echo "</tr>";
}

I want to have pagination with PHP for viewing this table , for example show every 10 line of text file in one page , line 1 to 10 in page 1 , line 11 to 20 in page 2 and etc ... how can i do this?
thanks

Amin Arjmand
  • 435
  • 7
  • 21

1 Answers1

1

You can use array_chunk (documentation);

array Chunks an array into arrays with size elements. The last chunk may contain less than size elements.

With that you change your code for:

$pages = array_chunk($lines, 10); // create chunk of 10 fr each page

foreach($pages as $i => $page) {
    echo "This is page num $i" . PHP_EOL;

    foreach ($page as $line) { // for each line in page
        $line=explode("-", $line);
        echo "<tr><td>$line[0]</td><td>$line[1]</td><td>$line[2]</td></tr>";
    }
}

Edited:

If you want to load only the data for specific page do:

$pageNum = _Session["page"]; // of whatever way you use to get page num - you may want to do -1 as array index starting from 0 - up to you
$pages = array_chunk(file('myfile.txt'), 10);

foreach ($pages[$pageNum] as $line) { // for each line in page you want
    $line=explode("-", $line);
    echo "<tr><td>$line[0]</td><td>$line[1]</td><td>$line[2]</td></tr>";
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
  • thanks, but how can i show page number with their content , your code echo page number 1 to last, i want when i load : ```site.com/?page=3``` it loads from line 31 until 40 , i want to know how can i do this? – Amin Arjmand Jun 17 '19 at 21:00
  • @AminArjmand - Edited with getting only the data for the require page - notice for the page 3 example you need to subtract 1 as the array index starting from 0 – dWinder Jun 17 '19 at 21:04