Unihedron
Unihedron

Reputation: 11041

Read a specific line in PHP?

I'm learning PHP. I want to find the fifth line from a file:

hello world
hey world
hi world
goodbye cruel world
hello user
hey user
...

I have reader.php:

<?php
$handle = @fopen("intro.txt");
$count = 5;
if ($handle) {
    while (--$count > 0) {
        fgets($handle);
    }
    echo fgets($handle);
    if ( !feof($handle)) {
        echo "Unexpected Exception";
    }
    fclose($handle);
}
?>

The file should be opened and $count is iterated through to move through --$count lines, so we can read the $count-eth line. I don't have a debugger to run.

But nothing is getting printed. Why?

Upvotes: 0

Views: 110

Answers (1)

Nisarg
Nisarg

Reputation: 3252

This one should work as you expect

$lines = file('intro.txt');
echo $lines[5];

Or for the fifth line:

echo $lines[4];

Upvotes: 2

Related Questions