读取文本文件并将行与完全相同的行进行比较返回false


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

我的当前代码:

$file = fopen("countries.txt","r");
$array = array();
while(!feof($file)) {
    $array[] = fgets($file);
}
fclose($file);
这是我的foreach循环:
$str = "test";
foreach ($array as $key => $val) {
    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }
}

我想知道为什么它只打印$val,如果它是数组的最后一个值。

例如,如果文本文件看起来像这样

test1
test2
test3
test

但是不工作,如果它看起来像这样

test1
test2
test
test3

问题是,在每行的末尾有一个新的行字符,所以:

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

这就是为什么它不像你期望的那样工作。

现在怎么解决?我可以介绍一下函数:file()。您可以将文件读入数组,并将标志设置为忽略每行末尾的新行。

所以把这些信息放在一起你会得到这个代码:

$array = file("countries.txt", FILE_IGNORE_NEW_LINES);
$str = "test";
foreach ($array as $key => $val) {
    if ($val == $str) {
        echo $val;
    } else {
        echo "not found";
    }
}

当你比较字符串时,你应该总是使用'==='