Jump to content

Print specific number of lines from a file.


yoob

Recommended Posts

There are many ways to do that, the best way depends on the size of the file, I think.

Small file:
[code]<?php
$output = array_slice(file($filepath), 0, 10);
?>[/code]
Do whatever you want with the new array..

Larger file:
[code]<?php
$handle = fopen("filename","r");

for($i=0;$line = fgets ($handle,4096) && $i<10;$i++){
  echo  $line;
}
?>[/code]

Making fgets part of the condition prevents you get errors when the file is shoter than 10 lines.
Hmm, another problem.

See, i have this small piece of line reverse code, making the bottom lines of the file show up at the top. I've put it together myself so it may not be perfect:

[code]<?

        $file=fopen("news/news.txt", "r");
        flock($file,1);

        $plik= array();
        while (!feof($file)){
                $plik[] = fgets($file,5000);
        }

        flock($file,3);
        fclose($file);

        for ($i=count($plik); $i>= 0; $i--){
        echo $plik[$i];
        }
?>[/code]

I try to merge it with the code you guys provided, but i dont think im skilled enough to understand all this. Could you help me out?
You're doing this:

for ($i=count($plik); $i>= 0; $i--){
        echo $plik[$i];

Saying:

start a loop
assign $i the value of the highest index in the array I want to fetch from
echo the value of my array that has index $i

keep looping, while $i is greater or equal than 0 doing the following:
for each loop, decrease $i by one
for each loop echo the value of my array that has index $i


resulting in, for say an array with 20 values:

$arr[20]
$arr[19]
$arr[18]
etc...

Get it?

You have to fetch the values in the same order you put them in there!
Alright. I studied the php.net manuals, and everything you said, and i came up with this little thing:

[code]        $number = count($plik)-10;

        for ($i=count($plik); $i>=$number ; $i--){
        echo $plik[$i];
        }
[/code]

And it works ^______^

Thanks a lot.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.