Question:
PHP 5 - Why does this print statement not do what I expect?
Smith
2010-02-20 06:53:35 UTC
I have the following print statement written in PHP

print "This spans\nmultiple lines. The newlines will be\noutput as well.";
?>

When I test the script I get the following output in the broweser

This spans multiple lines. The newlines will be output as well.

However the tutorial I am following insists it should come out like

This spans
multiple lines.The newlines will be
output as well.

This does in the source but not when displayed in the browser can you explain why please?
Three answers:
Thomas
2010-02-20 07:07:33 UTC
This will not work when outputting to a browser, because of the way that HTML works. "\n" is a newline character, but the HTML standard says that ANY whitespace character, including newlines, should be displayed as a space. That tutorial is just plain wrong, assuming the script is intended to be run via a browser (on the command line, \n would do what you expected).



To get a line break in HTML you need to use the
tag:




print "This spans
multiple lines. The newlines will be
output as well.";

?>
Brian K
2010-02-20 12:31:15 UTC
Well, to be precise, the script will indeed output



This spans

multiple lines.The newlines will be

output as well.



However, due to HTML interpretation of the output, all forms of white space are treated simply as white space (in the absence of more specific instructions, such as "
" tags, special CSS formatting, etc.). You will have similar output-versus-interpretation issues with tags, html entities, etc.




To see the actual output, use the "View Source" option or equivalent in your browser.
?
2016-05-31 22:16:58 UTC
I think you need a "
" in your output. e.g.: echo "$Count
"; EDIT for previous poster: In PHP, difference between single quote (') and double quote (") is that the content of the string between double quotes will be interpreted for variables, but the content between single quote is just verbatim without interpretation. E.g.: $myvar = 'MY DATA'; echo 'single quote $myvar'; // output single quote $myvar echp "double quote $myvar"; // output double quote MY DATA It just works out to be simpler and easier to read than concatenating all the variables and strings.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...