简体   繁体   中英

array not going through php function in_array

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');

  //var_dump($words);

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.

Instead of just

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

Use

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

flags

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.

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

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.

Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM