saplingPro
saplingPro

Reputation: 21329

unable to add line breaks. Why is it so?

The following script prints the strings from the array named arr. After an echo from arr I try to insert a line break using \n but I don't see it. Why is that ?

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "\n";
}

Upvotes: 1

Views: 137

Answers (5)

Austin Brunkhorst
Austin Brunkhorst

Reputation: 21130

Because line breaks are rendered in HTML with <br />. Do this instead.

foreach($arr as $var) {
    echo $var, '<br />';
}

An alternative would be to wrap the output in <pre></pre>, which evaluates whitespace and linebreaks like what you're doing currently.

Upvotes: 0

user1988903
user1988903

Reputation:

In HTML, the browser doesn't display \n linebreaks. If you view the source code, you will see them displayed. You can convert them to <br> using the nl2br PHP function, or by changing your script from this:

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "\n";
}

to this:

<?php
$arr = array("ghazal","shayari","silence","hayaat");
echo $arr[0];
echo $arr[1];
foreach($arr as $var) {
  echo $var;
  echo "<br>";
}

And if this doesn't work for you, you could always use the pre HTML tag. The pre tag retains the \n linebreaks, and makes them visible.

If this helps, please mark this answer as correct by clicking the check next to this question.

Thanks. :)

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Presumably your PHP script is generating HTML that is viewed in a web browser. And, as we know, extraneous whitespace in HTML doesn't get rendered on screen.

Either generate plain text (header("Content-type: text/plain")) or output, instead of '\n', something that renders a line break in HTML (e.g. <br />).

Upvotes: 1

user229044
user229044

Reputation: 239311

HTML treats all whitespace characters, in any number, identically.

That is, the following will all render as a single space in the browser:

echo "\n";
echo "\t";
echo "         ";
echo "  \n\n\n  ";

In order to render an actual linkbreak in HTML, you need to insert a <br> element into your document.

Upvotes: 2

jogesh_pi
jogesh_pi

Reputation: 9782

this should work

foreach($arr as $var) {
  echo $var;
  echo "<br />";
}

because in your HTML section <br /> work for linebreak, your \n also works when you see the source code of HTML from browser's side that time it shows you the linebreak

Upvotes: 0

Related Questions