1

I am trying to alphabetize then remove duplicates out of this array. Then I am trying to write each element in the array to its own line in a text file.

Meaning only one element of the sorted and unique array will be on a line.

But all I am getting is a blank text file.

How can I write the contents of this array, $sorted_lines to a text file so that each element is on a new line?

Here is my code:

<?php
$lines = file('american.txt');
$lines = array_walk($lines, 'trim'); 
$sorted_lines = sort(array_unique($lines));
$out = fopen("new.txt", "w");
foreach($sorted_lines as $line){
    $line .= "\n";
    fwrite($out, $line);
}
?>
1
  • Try throwing some debug information in there. First, are there lines to begin with? Do a print_r on $lines and see if there is anything there. Second, surround the fopen in an IF. if (fopen("new.txt", "w")) { //do work } Third, close the handle. fclose($out); Commented Jun 7, 2013 at 15:15

2 Answers 2

2

array_walk() and sort() are both pass by reference , with the return value being a boolean true/false for success/failure

array_walk($lines, 'trim');
$sorted_lines = array_unique($lines);
sort($sorted_lines);
Sign up to request clarification or add additional context in comments.

Comments

1

In the functions array_walk() and sort(), the first parameter is passed by reference, not value. This means that the function directly modifies the first parameter, instead of returning the result. array_walk() returns a boolean indicating whether or not the function works, not the array; therefore, the function is setting $lines=1. sort() does the same thing.

In the PHP documentation, you can tell that a parameter is passed by reference by it being preceeded by an ampersand; for example, the sort declaration looks like this:

bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Note now the first parameter is &$array, not $array. This is the same way you declare references in custom functions.

Comments

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.