array not going through php function in_array

3019 views php

I inserted, using the file(), words from a .txt file into an array. According to var_dump() the values are strings, and print_r give me a normal one dimension array.

  $words = file('stopWords.txt');


When I try something like:

 if( in_array('able', $words) ) {
       echo "match found";

Nothing happens, I've tried making a test array with and it works fine. The array that $word outputs has 636 elements in it. Maybe that has something to do? Although I doubt it because I've tried it with a larger array and it still worked. I'm not sure what's causing this to happen, it seems to only have problems with this specific array. Can someone please help me out here, thanks.

answered question

can you provide an example of var_dump($words); output?

FILE_IGNORE_NEW_LINES - AKA Omit newline at the end of each array element. able != able\n Or in other words $words = file('stopWords.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_L‌​INES);

the array is really big so var_dump outputs a lot, do you wants just a snippet?

@ArtisticPhoenix how and why did this work?! Thank you so much

It's magic. It's because the return has line endings, and in array is not fuzzy.

I'll look more into this, but thanks again

1 Answer


Instead of just

 $words = file('stopWords.txt');


$words = file('stopWords.txt',FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);


The optional parameter flags can be one, or more, of the following constants:

FILE_USE_INCLUDE_PATH Search for the file in the include_path.

FILE_IGNORE_NEW_LINES Omit newline at the end of each array element

FILE_SKIP_EMPTY_LINES Skip empty lines

This is the most relevant one Omit newline at the end of each array element.

Basically this is what you are doing:

if( in_array('able', ["able\n"]) ) {
   echo "match found";

Which is false. Or in other words its not exactly equivalent to doing explode("\n", $contents) as the line (array items) still contain the newline. Which because in_array is not a fuzzy search (basically its ==) it won't match them 'able' != 'able\n'.

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used.

You could also trim the items in the array like this $words=array_map('trim', $words); but why bother when there is a flag for it.


posted this

Have an answer?


Please login first before posting an answer.