Reading text file and comparing line with the exact same line returns false

前端 未结 2 754
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 00:20

My current code:

$file = fopen(\"countries.txt\",\"r\");
$array = array();

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

fclose($file);
相关标签:
2条回答
  • 2020-12-12 00:37

    When you compare strings - you should always use '==='.

    0 讨论(0)
  • 2020-12-12 00:44

    The problem is, that you have a new line character at the end of each line, so:

    test\n !== test
      //^^ See here
    

    That's why it doesn't work as you expect it to.

    How to solve it now? Can I introduce to you the function: file(). You can read a file into an array and set the flag to ignore these new lines at the end of each line.

    So putting all this information together you will get this code:

    $array = file("countries.txt", FILE_IGNORE_NEW_LINES);
    $str = "test";
    
    foreach ($array as $key => $val) {
    
        if ($val == $str) {
            echo $val;
        } else {
            echo "not found";
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题