user191688
user191688

Reputation: 2659

why is array_unique not working after array_unshift?

Or maybe I'm doing something else wrong.

<?php
$date = "2011-12-31|12-31";

$fileData = file('something.txt'); // Get file contents as array
print_r($fileData);
echo "<br /><br />";

array_unshift($fileData, $date); // Add date to [0]
print_r($fileData);
echo "<br /><br />";

$cleanData = array_unique($fileData); // remove dupes
print_r($cleanData);
echo "<br /><br />";
?>

Prints out as:

Array ( [0] => 2011-12-31|12-31 [1] => 2011-12-30|12-30 [2] => 2011-12-29|12-29 ) 

Array ( [0] => 2011-12-31|12-31 [1] => 2011-12-31|12-31 [2] => 2011-12-30|12-30 [3] => 2011-12-29|12-29 ) 

Array ( [0] => 2011-12-31|12-31 [1] => 2011-12-31|12-31 [2] => 2011-12-30|12-30 [3] => 2011-12-29|12-29 ) 

Here is something.txt:

2011-12-31|12-31
2011-12-30|12-30
2011-12-29|12-29

I suspect that there might be eol or lf markers in the $fileData. If this is the case, is there an easy way to remove them?

Upvotes: 2

Views: 116

Answers (1)

user142162
user142162

Reputation:

The strings in the array returned by file() have new line characters at the end, making them not equal to strings which do not. You can tell file() to not include these characters by adding FILE_IGNORE_NEW_LINES as the 2nd parameter:

file('something.txt', FILE_IGNORE_NEW_LINES);

Upvotes: 3

Related Questions