Django Johnson
Django Johnson

Reputation: 1449

Write array elements on new line in text file

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);
}
?>

Upvotes: 1

Views: 2694

Answers (2)

IanPudney
IanPudney

Reputation: 6021

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.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212412

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);

Upvotes: 2

Related Questions