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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With