Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

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

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

test
 !== 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";
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...