user3038431
user3038431

Reputation: 113

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

Upvotes: 3

Views: 72

Answers (2)

koredalin
koredalin

Reputation: 445

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

Upvotes: 0

Rizier123
Rizier123

Reputation: 59701

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

}

Upvotes: 6

Related Questions