Search code examples
phparraysfileline-endings

Unwanted line endings when calling file()


I'm trying to merge array elements imported from a multi-line text file, separated by commas:

$ cat input.txt 
one,two,three,four
red,blue,green
human,klingon,dolphin

What I want to get is a single array with 10 items in it. The code I've tried is this:

<?php

$fa=file("input.txt");
$w=array();
foreach($fa as $combo) {
    $w=array_merge($w,explode(",",$combo));
}
print_r($w);

?>

The problem is, I seem to be getting returns after line endings:

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four

    [4] => red
    [5] => blue
    [6] => green

    [7] => human
    [8] => klingon
    [9] => dolphin

)

Why are the spaces there? How do I get rid of them?


Solution

  • They're not spaces, they're newlines (\n).

    Everything in the input file is represented in your array, it's just split into array elements. The file() function parses your file line-by-line, and each line pulled in by file() includes a character that ends the line.

    It sounds like you want to trim() off the whitespace. Note that this has the added benefit of removing trailing spaces and tabs.

        $w=array_merge($w,explode(",",trim($combo)));
    

    Does that give the results you want?