读取文本文件并用相同的一行行比较返回false [英] Reading text file and comparing line with the exact same line returns false
问题描述
我目前的code:
$文件=的fopen(countries.txt,R);
$阵列=阵列();而(!的feof($文件)){
$数组[] =与fgets($文件);
}FCLOSE($文件);
下面是我的foreach循环:
$海峡=测试;的foreach($数组$关键=> $ VAL){ 如果($ VAL == $ STR){
回声$ VAL;
}其他{
回声未找到;
}}
我想知道为什么它仅仅是打印$ VAL如果是数组的最后一个值。
例如,它的工作原理,如果txt文件看起来像这样
TEST1
TEST2
TEST3
测试
但如果它看起来像这样不工作
TEST1
TEST2
测试
TEST3
的问题是,你必须在每行的最后一个新行字符,因此:
测试\\ N!==测试
// ^^看到这里
这就是为什么它,你指望它不能正常工作。
如何到现在解决呢?我可以向你介绍功能: 文件()
。可以读取一个文件到一个数组,并设置标志在每行的末尾忽略这些新的生产线。
于是将所有这些信息一起,你会得到这个code:
$阵列=文件(countries.txt,FILE_IGNORE_NEW_LINES);
$海峡=测试;的foreach($数组$关键=> $ VAL){ 如果($ VAL == $ STR){
回声$ VAL;
}其他{
回声未找到;
}}
My current code:
$file = fopen("countries.txt","r");
$array = array();
while(!feof($file)) {
$array[] = fgets($file);
}
fclose($file);
Here is my foreach loop:
$str = "test";
foreach ($array as $key => $val) {
if ($val == $str) {
echo $val;
} else {
echo "not found";
}
}
I am wondering why it is only printing $val if it is the last value of the array.
For example, it works if the txt file looks like this
test1
test2
test3
test
but doesn't work if it looks like this
test1
test2
test
test3
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";
}
}
这篇关于读取文本文件并用相同的一行行比较返回false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!