0

I found that linebreak solution here

a) But the result of the echo has no linebreaks, what is wrong?

b) Can I do linebreaks in the echo as well?

PHP

<?php
$var = "Hi there\nWelcome to my website\n";
echo $var;
 ?>
Community
  • 1
  • 1
user2952265
  • 1,590
  • 7
  • 21
  • 32

5 Answers5

6

Linebreak \n works when you run your script in console where this code means line break. Depending on the OS it can be \n, \r or \r\n. It will also work in web, in <PRE> block. Otherwise you must use <br /> or call nl2br() function on your string to tell PHP to do that for you.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
4

Usually \n line breakings are used in CLI mode. I suppose you are using it through the web browser, so you can use HTML as it's primary used to control the view. $var = "Hi there <br /> Welcome to my website <br />";

Royal Bg
  • 6,988
  • 1
  • 18
  • 24
3

Use html break element <br/> to print line break. For detailed information look at MDN

test1604
  • 620
  • 4
  • 12
  • 31
3

you have different ways to do it.

First...

$var = "Hi there <br /> Welcome to my website <br /> ";
echo $var;

Second is

$var = "Hi there \n Welcome to my website \n ";
echo nl2br($var);

And also third one

$var = "Hi there ".PHP_EOL." Welcome to my website".PHP_EOL;
echo nl2br($var);

PHP_EOL is php constant and its value is \n.

get the description of nl2br http://pk1.php.net/nl2br

http://www.w3schools.com/php/func_string_nl2br.asp

And also see this it is very useful

http://www.go4expert.com/articles/difference-n-rn-t8021/

Remember: In file writing <br> doesn't work only \n will work \n means new line but if you are using html <br> tag is helpful.

user2727841
  • 715
  • 6
  • 21
0

Try this:

<?php
  $var = "Hi there\nWelcome to my website\n";
  echo nl2br($var);
 ?>

Line breaks in HTML are not rendered by browsers, so you'll need a <br/>-tag. the nl2br() function will provide that for you in case your text doesn´t have it before.

jtheman
  • 7,421
  • 3
  • 28
  • 39