Josh Poor
Josh Poor

Reputation: 533

How to read separate lines from a file in PHP (fopen)

The code is taken from hackerrank.com

Content inside file name php://stdin

5 4
1 2 3 4 5

Code:

<?php

$handle = fopen ("php://stdin", "r");


fscanf($handle, "%i %i", $n, $d);
$a_temp = fgets($handle);
$a = explode(" ",$a_temp);

print_r($a_temp);

?>

Output:

1 2 3 4 5

I am confused, why the code only reads the second line (i.e 1 2 3 4 5), not first line? How to read both the lines? or Just first one?

Upvotes: 0

Views: 333

Answers (2)

Mohammad
Mohammad

Reputation: 497

Another way to get out

$handle = fopen ("php://stdin");

$numbers = str_replace("\n", ' ', $handle);
$numbers = explode(' ', $numbers);

foreach($numbers as $key => $value) 
    if($value == '')
        unset($numbers[$key]);

echo '<pre>';
print_r($numbers);

Output :

Array
(
    [1] => 5
    [2] => 4
    [3] => 1
    [4] => 2
    [5] => 3
    [6] => 4
    [7] => 5
)

Upvotes: 1

josemmo
josemmo

Reputation: 7073

The code works just fine.

Each time you call fscanf you are reading one line of the file. This means that, after fscanf($handle, "%i %i", $n, $d) is executed, the file pointer jumps to the second line.

Check variables $n and $d and both should be equal to 5 and 4, respectively.


If you were to read and parse all lines, avoid using fscanf as the pattern is not the same for each line:

$handle = fopen("php://stdin", "r");
while ($line = fgets($handle)) {
  $a = explode(" ", $line);
  var_dump($a);
}

Upvotes: 2

Related Questions