[英]What is the difference between these two arrays?
I have a plain text file called 'list.txt', the content of which is then stored inside a variable $array1 by using file().我有一个名为“list.txt”的纯文本文件,然后使用 file() 将其内容存储在变量 $array1 中。 The text file contains the following:
文本文件包含以下内容:
12088
10118
10182
12525
58162
11821
17533
10118
I also declare another array variable called $array2 with a similar content:我还声明了另一个名为 $array2 的数组变量,其内容类似:
$array2 = array(
'12088',
'10118',
'10182',
'12525',
'58162',
'11821',
'17533',
'10118'
);
When I run this function, it shows nothing.当我运行这个函数时,它什么也没显示。
$needle = "12088";
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
However, when I swap it to $array2, the script shows "Found in array2!".但是,当我将它交换到 $array2 时,脚本显示“在 array2 中找到!”。
Here is what the script looks like:脚本如下所示:
$array1 = file('list.txt');
$array2 = array(
'12088',
'10118',
'10182',
'12525',
'58162',
'11821',
'17533',
'10118'
);
$needle = "12088";
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
if ( in_array($needle, $array2) ) {
echo 'Found in array2!';
}
What is the difference between these two arrays that causes the $needle to be found in one array, and not the other?这两个数组之间的区别是什么导致 $needle 出现在一个数组中,而不是另一个?
The difference is that you have \\r\\n symbols presented in list.txt.不同之处在于您在 list.txt 中显示了 \\r\\n 个符号。
Try to use $array1 = array_map('trim', $array1)
before尝试使用
$array1 = array_map('trim', $array1)
之前
if ( in_array($needle, $array1) ) {
echo 'Found in array1!';
}
You need to convert the file to an array first.您需要先将文件转换为数组。 You can use
str_getcsv
, like this:您可以使用
str_getcsv
,如下所示:
Ref: str_getcsv参考: str_getcsv
$file = file_get_contents('test.txt');
// Separator set as new line "\n"
$array = str_getcsv($file, "\n");
var_dump($array);
// Output
array:8 [▼
0 => "12088"
1 => "10118"
2 => "10182"
3 => "12525"
4 => "58162"
5 => "11821"
6 => "17533"
7 => "10118"
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.