Home > Software design >  What is the difference between these two arrays?
What is the difference between these two arrays?

Time:10-30

I have a plain text file called 'list.txt', the content of which is then stored inside a variable $array1 by using file(). 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 = 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!".

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?

CodePudding user response:

The difference is that you have \r\n symbols presented in list.txt.

Try to use $array1 = array_map('trim', $array1) before

if ( in_array($needle, $array1) ) {
    echo 'Found in array1!';
}

CodePudding user response:

You need to convert the file to an array first. You can use str_getcsv, like this:

Ref: 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"
]
  • Related