Home > Back-end >  php function fgets() unexpectet result
php function fgets() unexpectet result

Time:12-26

#!/usr/bin/php
<?php

    define("KPA_PEOPLE","/devel/pic/snk_db2/KPA-migration/Keywords/gettingTheKeywordsAndFiles/KPA_People.txt");
    $hndl_kpa_people=fopen(KPA_PEOPLE,"r ") or die("Failed opening ".KPA_PEOPLE);
    while($line=fgets($hndl_kpa_people)!==FALSE){
    echo "\nline: ".$line."\n";
}
?>
Context: 
The file looks like this in the file system:
-rw-r--r-- 1 snkdb snkdb   6096 dec 25 14:08 KPA_People.txt
(I'm the user snkdb)

The file's contents looks like:
et|2
Elisabet|3
okända|4...

The result looks like:

line: 1

line: 1

line: 1...

the expected result was:

et|2

Elisabet|3

okända|4... 

as far as I understand the "while($line=fgets($hndl_kpa_people)!==FALSE)" follows the convention in the manual and looks like it works in earlier scripts. Any thoughts would be appreciated!


CodePudding user response:

In the following line:

while($line=fgets($hndl_kpa_people)!==FALSE)

PHP is first evaluating the expression fgets($hndl_kpa_people)!==FALSE and then assigns it to the variable $line.

Furthermore, it is redundant to evaluate if something inside the while loop is different from false, since while loop runs while the condition it's evaluating is true.

So the line should be:

while($line = fgets($hndl_kpa_people))

You can read more on Operator Precedence in the official documentation: https://www.php.net/manual/en/language.operators.precedence.php

You can read more about while loop here: https://www.php.net/manual/en/control-structures.while.php


Edit: Since there is a confusion in the comments whether reading an empty line will return false - it will not. Take the following simple example:

<?php

$file = fopen('sample.txt', "r ");
$counter = 0;
while ($line = fgets($file)) {
    print_r("Counter: $counter - Line: " . $line);
    $counter  ;
}
fclose($file);

with the following sample file:

test 123

test 234
test 345

The result from execution is:

Counter: 0 - Line: test 123
Counter: 1 - Line: 
Counter: 2 - Line: test 234
Counter: 3 - Line: test 345

CodePudding user response:

Thank you guys! Both answers are good contributions. Nikola got the problem and Nigel presented the effective solution. I hope you have some free time also, during the holiday.

  •  Tags:  
  • php
  • Related