Php add new line with implode

I am trying to add a new line \n to my foreach statement using implode.

My code is:

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

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

I am trying to get something like this:

['Country', 'number'],

['Country', 'number'],

['Country', 'number']

However, I get the following:

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

Why is my \ n not calling a new line?

+6
source share
4 answers

I suspect this is because you are echoing the data to the browser and not showing the line break as you expect. If you wrap your implode in <pre> tags, you will see that it works correctly.

In addition, your arguments are returned to your implode according to the current documentation. However, for historical reasons, the parameters can be in any order.

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

Output:

 this, is, an, array 
+13
source

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 write directly in HTML (this does not work with files), it is possible to use <br> as follows:

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

It may also work.

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

Output:

 one two three four 
0
source

Many others claim that you are using the wrong order, this is only a partial right, because the documents recommend it only, but you do not need:

implode () may, for historical reasons, accept its parameters into the order. However, for consistency with explode (), this may be less embarrassing to use a documented argument order.

I think your problem is caused by the way browsers interpret HTML. They don’t care about the news; they are their usual place.

To show these line breaks, you can use <pre><?php echo implode($glue, $array); ?></pre> <pre><?php echo implode($glue, $array); ?></pre> . You can also use nl2br(implode(..)) or nl2br(implode(..), true) if you are writing XHTML.

-1
source

All Articles