Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array file isset Incorrectly Returning False

Tags:

arrays

php

isset

I have the following PHP code:

$haystack  = file("dictionary.txt");
$needle = 'john';
$flipped_haystack = array_flip($haystack);
if (isset($flipped_haystack[$needle])) {
    echo "Yes it's there!";
}
else {
    echo "No, it's not there!";
}

The contents of dictionary.txt are as follows (UTF-8 encoded):

john

For some reason I keep getting false despite the fact that $haystack prints out without any problem. It's just the false that I keep getting which keeps giving me issues. Alternately, I tried changing $haystack to the following code which in turn correctly returned as true:

$haystack = array("john");

Why is my code wrongly returning false?

like image 731
Pamela Avatar asked Jan 14 '23 22:01

Pamela


1 Answers

It's probably because of the line breaks at the end of each element. Try this:

$haystack  = file("dictionary.txt", FILE_IGNORE_NEW_LINES);

Here is a note from the PHP Manual:

Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you do not want the line ending present.
like image 106
rationalboss Avatar answered Jan 19 '23 12:01

rationalboss