Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP, add a newline with implode

Tags:

php

implode

I'm trying to add a newline \n, in my foreach statement with implode.

My code:

$ga->requestReportData($profileId,array('country'),array('visits')); 
$array = array();
foreach($ga->getResults() as $result){ 
    $array[] = "['".$result->getcountry()."', ".$result->getVisits()."]"; 
} 
echo implode(",\n", $array);

I only get a comma and a space between my results. I want a comma and a newline.

I am trying to get something like this:

['Country', 'number'],

['Country', 'number'],

['Country', 'number']

However I I get this:

['Country', 'number'], ['Country', 'number'], ['Country', 'number']

Why does my \n not cause a newline?

like image 239
Mathieu Avatar asked Feb 05 '14 17:02

Mathieu


3 Answers

I suspect it is because you are echoing the data to the browser and it's not showing the line break as you expect. If you wrap your implode in the the <pre> tags, you can see it is working properly.

Additionally, your arguments are backwards on your implode function, according to current documentation. However, for historical reasons, parameters can be in either order.

$array = array('this','is','an','array');
echo "<pre>".implode(",\n",$array)."</pre>";

Output:

this,
is,
an,
array
like image 166
Andy Avatar answered Oct 18 '22 04:10

Andy


For cross-platform-compatibility use PHP_EOL instead of \n.

Using the example from the accepted answer above:

$array = array('this','is','another','way');
echo "<pre>".implode(PHP_EOL, $array)."</pre>";

If you're writing directly to HTML (it wouldn't work on files) there is an option of using <br> like this:

$array = array('this','is','another','way');
echo "<p>".implode(<br>, $array)."</p>";

Both output:

this, 
is, 
another, 
way
like image 28
boroboris Avatar answered Oct 18 '22 02:10

boroboris


This can also work

$array = array('one','two','three','four');
echo implode("<br>", $array);

Output:

one
two
three
four
like image 31
B.K Avatar answered Oct 18 '22 03:10

B.K