Search code examples
phparraysexplodefgetsarray-reverse

Making array_reverse when using fgets | text file


I want to reorder my array from last bottom line to first on the top. I'm trying use array_reverse, but i fail all runs.

Anyone of you, have an idea how i could implement this into my code? Everything works, but i only need array in reverse

Thanks

this is my code:

<?php
$f = fopen("list.txt", "r");

while (!feof($f)) { 

$arrM = explode("###",fgets($f));

echo "<p align='center'><b><font color='red' size='6'>" . $arrM[5]. " PLN</font></b><br><b><font size='5'>" . $arrM[3]. "</b></font><br><a target='_blank' href='" . $arrM[1] . "'><img src=" . $arrM[2]. " width='100%' /></a><br><br><br><br></p>";

}

fclose($f);
?>

Solution

  • Try This

     <?php
    $data = [];
    
    $f = fopen("list.txt", "r");
    
    // store all data line by line in a 2D array
    while (!feof($f)) { 
        $data[] = explode("###",fgets($f));
    }
    
    // reverse your data array
    $arrM = array_reverse($data);
    
    // echo data
    foreach ($arrM as $row) {
        echo "<p align='center'>
        <b><font color='red' size='6'>" . $row[5]. " PLN</font></b><br>
        <b><font size='5'>" . $row[3]. "</b></font><br>
        <a target='_blank' href='" . $row[1] . "'><img src=" . $row[2]. " width='100%' /></a></p>";
    }
    
    fclose($f);  ?>