Reading a text file and comparing a string to the same string 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 only prints $ 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
test1
test2
test
test3
+3
user3038431
source
to share
2 answers
The problem is that you have a new line character at the end of each line, so:
test\n !== test
//^^ See here
This is why it doesn't work the way you expect.
How to solve this now? May I introduce you to a function: file()
. You can read the file into an array and set a flag to ignore these new lines at the end of each line.
So by putting all this information together, you end up with 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";
}
}
+6
Rizier123
source
to share
When comparing strings, you should always use '==='.
0
koredalin
source
to share