2

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?

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

It's easier to spot these kind of issues if you user var_dump() and your browser's View Source feature (rather than the print_r() rendered as HTML).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.