Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 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 Answer

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";
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...