Isset array file Returns False

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 there!"; } else { echo "No, it not there!"; } 

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

 john 

For some reason, I keep making mistakes, even though $haystack prints without problems. It’s just a lie that I keep getting, that keeps giving me problems. As an alternative, I tried changing $haystack to the following code, which in turn will correctly return as true:

 $haystack = array("john"); 

Why is my code mistakenly returning false?

+4
source share
4 answers

This is likely due to line breaks at the end of each element. Try the following:

 $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. 
+4
source

The problem is based on the fact that file :

Returns a file in an array. Each element of the array corresponds to a line in the file, with a new line.

Therefore, john not equal to john\n .

Just set the following flag:

 file("dictionary.txt", FILE_IGNORE_NEW_LINES); 
+2
source

The file() function adds new line elements to array elements.

See the manual page: http://www.php.net/manual/en/function.file.php

Open the file as follows:

 $haystack = file('dictionary.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 

In addition, to help with debugging, you can add lines like this:

 var_dump($haystack); var_dump($flipped_haystack); 

What would you show this:

 array(1) { [0] => string(5) "john\n" } array(1) { 'john ' => int(0) } No, it not there! 
+2
source

Use the FILE_IGNORE_NEW_LINES parameter, as some newline characters may appear in a file read in an array

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

http://php.net/manual/en/function.file.php

+1
source

All Articles