phparrayspaginationpage-numbering

how can i set page number in showing contents of text file


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


Solution

  • 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>";
    }