简体   繁体   English

数组不通过PHP函数in_array

[英]array not going through php function in_array

I inserted, using the file(), words from a .txt file into an array. 我使用file()将.txt文件中的单词插入到数组中。 According to var_dump() the values are strings, and print_r give me a normal one dimension array. 根据var_dump(),值是字符串,而print_r给我一个普通的一维数组。

  $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. $ word输出的数组中有636个元素。 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_USE_INCLUDE_PATH在include_path中搜索文件。

FILE_IGNORE_NEW_LINES Omit newline at the end of each array element FILE_IGNORE_NEW_LINES在每个数组元素的末尾省略换行符

FILE_SKIP_EMPTY_LINES Skip empty lines FILE_SKIP_EMPTY_LINES跳过空行

This is the most relevant one Omit newline at the end of each array element . 这是Omit newline at the end of each array element最相关的一个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 . 这是false Or in other words its not exactly equivalent to doing explode("\\n", $contents) as the line (array items) still contain the newline. 换句话说,它并不完全等同于执行explode("\\n", $contents)因为该行(数组项)仍包含换行符。 Which because in_array is not a fuzzy search (basically its == ) it won't match them 'able' != 'able\\n' . 因为in_array不是模糊搜索(基本上是== ),所以不会匹配它们'able' != 'able\\n'

Note: Each line in the resulting array will include the line ending, unless FILE_IGNORE_NEW_LINES is used. 注意:除非使用FILE_IGNORE_NEW_LINES,否则结果数组中的每一行都将包含行尾。

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

You could also trim the items in the array like this $words=array_map('trim', $words); 您也可以像这样修改数组中的项目$words=array_map('trim', $words); but why bother when there is a flag for it. 但是为什么要打扰当有一个标志。

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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