John Griffis Jr.
John Griffis Jr.

Reputation: 39

PHP Read File Line By Line and output to 1 line

I am trying to get a file that looks like this:

Name1

Name2

Name3

and want it to output like so:

Name1, Name2, Name3

I tried this but am getting nowhere with it:

    $list = file_get_contents("tready.txt");
$convert = explode("\n", $list);
for ($i=0;$i<count($convert);$i++)  
{
    $list = $convert[$i].', '; //write value by index
}
$this->say('Currently waiting: ' . $list);
}

Upvotes: 0

Views: 46

Answers (4)

AbraCadaver
AbraCadaver

Reputation: 78994

Easier:

$list = implode(', ', file('tready.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));

Upvotes: 1

Oleg Dubas
Oleg Dubas

Reputation: 2348

Even easier:

echo str_replace("\n", ', ', file_get_contents("tready.txt"));

Upvotes: 0

Alain
Alain

Reputation: 36954

Something like that?

$list = file("tready.txt", FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES);
echo implode(", ", $list);

Docs: file, implode

Upvotes: 1

cyborg86pl
cyborg86pl

Reputation: 2617

You'll achieve that simply with that code:

$list = file_get_contents("tready.txt");
$convert = implode(', ', explode("\n", $list));

What's happening here: you merge elements of an array (exploded $list) with , string.

Upvotes: 0

Related Questions