This is the code inside my PHP loop:
echo 'Name: ' . $name . '<br/>';
How do I cause the PHP to begin a new HTML line with each iteration of the loop (instead of printing everything on a single HTML line)?
You need to include newline characters in your output. Thus:
echo 'Name: ' . $name . "<br/>\n";
Note the double quotes, which are necessary for the escaped \n to appear as a newline character instead of a literal \n.
Another useful escape is \t, which inserts tabs into your output.
Lastly, as an unrelated tip, it is faster to pass multiple strings to echo
with commas instead of periods, like so:
echo 'Name: ', $name ,"<br/>\n";
This is because using the dot causes PHP to allocate a new string buffer, copy all of the separate strings into that buffer, and then output this combined string; whereas the comma causes PHP to simply output the strings one after another.
try this:
echo 'Name: ' . $name . '<br/>'."\n";
The \n is a newline character if in double quotes.
i find that using single quotes is easier than using ."\n" for example using
echo 'text'.$var.'<br />
next line';
new line characters are echoed if they are within single quotes
You can insert newline characters that will appear in HTML source code by including literal carriage returns in your PHP strings, eg:
$count1 = '1';
$count2 = '2';
/* Note the opening single quote in the next line of code is closed on
the following line, so the carriage return at the end of that line is
part of the string */
echo '<table>
<tr><td>This is row</td><td>' , $count1 , '</td><td>and</td></tr>
<tr><td>this is row</td><td>' , $count2 , '</td><td> </td></tr>
</table>';
will output
This is row 1 and
this is row 2
as you'd expect, but the source code will presented as:
<table>
<tr><td>This is row</td><td>1</td><td>and</td></tr>
<tr><td>this is row</td><td>2</td><td> </td></tr>
</table>
Trivial example maybe, but when you're echoing a large string with several lines (like a table), it's easier to debug the HTML source if these line breaks are present. Note that, if you indent with tabs or spaces within these strings, the HTML code will also have these indents. Of course, the browser will collapse all of them into single spaces, but it makes the HTML code easier to follow.