$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;"
echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol
so something thats more readable and elegant to use?
Thanks
$var = "Hi there"."<br/>"."Welcome to my website"."<br/>;"
echo $var;
Is there an elegant way to handle line-breaks in PHP? I'm not sure about other languages, but C++ has eol
so something thats more readable and elegant to use?
Thanks
Because you are outputting to the browser, you have to use <br/>
. Otherwise there is \n
and \r
or both combined.
For linebreaks, PHP as "\n"
(see double quote strings) and PHP_EOL
.
Here, you are using <br />
, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : ne need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br()
function, to convert \n
to <br>
.
Well, as with any language there are several ways to do it.
As previous answerers have mentioned, "<br/>"
is not a linebreak in the traditional sense, it's an HTML line break. I don't know of a built in PHP constant for this, but you can always define your own:
// Something like this, but call it whatever you like
const HTML_LINEBREAK = "<br/>";
If you're outputting a bunch of lines (from an array of strings for example), you can use it this way:
// Output an array of strings
$myStrings = Array('Line1','Line2','Line3');
echo implode(HTML_LINEBREAK,$myStrings);
However, generally speaking I would say avoid hard coding HTML inside your PHP echo/print statements. If you can keep the HTML outside of the code, it makes things much more flexible and maintainable in the long run.
Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.
Example:
$myoutput = "After this sentence there is a line break..|.. Here is a new line.";
$myoutput = str_replace(".|..","<br />",$myoutput);
or how about:
$myoutput = "After this sentence there is a line break.E(*)3 Here is a new line.";
$myoutput = str_replace("E(*)3","<br />",$myoutput);
I call the first method "middle finger style" and the second "goatse style".