0

I'm familiar with programming in general but what I'm facing is a bit weird. The if statement is only working on the last iteration:

Output: IN IN OUT OUT OUT OUT IN OUT IN BIN BOUT OUT OUT OUT OUT

However if I add an if statement it only performs on the last iteration:

<?php

$conn = mysqli_connect('localhost','root','','text');

if(!$conn)
{
    die(mysqli_error());
}


$open = fopen('test.txt','r');
while (!feof($open)) 
{
    
    $getTextLine = fgets($open);
    $explodeLine = explode(",",$getTextLine);
    list($Date,$ID,$Status) = $explodeLine;
    
    if($Status == "OUT"){
        echo "$Status";
    }

}
fclose($open);
?>

Output: OUT

Text file:

19-04-21 13:41:38  ,0000000917         ,IN
19-04-21 13:49:50  ,0000001310         ,IN
19-04-21 13:52:24  ,0000000505         ,OUT
19-04-21 13:53:36  ,0000000546         ,OUT
19-04-21 14:05:24  ,0000001267         ,OUT
19-04-21 14:05:32  ,0000001228         ,OUT
19-04-21 14:06:26  ,0000000454         ,IN
19-04-21 14:13:10  ,0000000990         ,OUT
19-04-21 14:17:32  ,0000001354         ,IN
19-04-21 14:27:04  ,0000000325         ,BIN
19-04-21 14:27:18  ,0000000325         ,BOUT
19-04-21 14:31:12  ,0000000649         ,OUT
19-04-21 14:32:22  ,0000000061         ,OUT
19-04-21 14:33:00  ,0000001301         ,OUT
19-04-21 14:34:34  ,0000000548         ,OUT
Spectre
  • 47
  • 8
  • 2
    The `fgets()` function includes whatever newline characters are in the file, so `$Status` is probably equal to `"OUT\n"` on every line but the last. You can use `trim()` to fix that. – Alex Howansky Aug 11 '21 at 13:42
  • 1
    As an aside: `mysqli_error()` won't report connection errors - because it _requires_ a connection object passed into it. `mysqli_connect_error()` is what you need to show connection errors. And do you even need a DB connection here? You're only reading from a file, not a database. – ADyson Aug 11 '21 at 13:42
  • [Why `while (!feof($open))` is wrong](https://stackoverflow.com/questions/34425804/php-while-loop-feof-isnt-outputting-showing-everything) – Barmar Aug 11 '21 at 13:47
  • Also note, if you split on just a comma, `$Date` and `$ID` will have all those spaces included at the end. If this is an issue, you can do something like `preg_split('/\s*,\s*/', $line)`. – Alex Howansky Aug 11 '21 at 13:48
  • @AlexHowansky the output for the first piece of code is: IN IN OUT OUT OUT OUT IN OUT IN BIN BOUT OUT OUT OUT OUT. However, I want to handle the data for example by adding an if statement, it only works for the last Iteration. – Spectre Aug 11 '21 at 13:56
  • It works for the last iteration because the file doesn't have a newline on the last line. – Alex Howansky Aug 11 '21 at 13:59

0 Answers0