0

Experimenting with arrays and wondering why the following DOESN'T seem to print the values on SEPARATE lines when I run it?

<?php

$my_array = array("stuff1", "stuff2", "stuff3");

echo $my_array[0] . "\n";
echo $my_array[1] . "\n";
echo $my_array[2] . "\n";

?>
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Tim
  • 1,056
  • 4
  • 17
  • 34

5 Answers5

5

This makes the trick.

<?php
    $my_array = array("stuff1", "stuff2", "stuff3");
    foreach ( $my_array as $item ) {
        echo $item . "<br/>";
    }
?>
hugohabel
  • 724
  • 6
  • 17
3

If your viewing the output in a web browser, newlines aren't represented visually. Instead you can use HTML breaks:

<?php
    $my_array = array("stuff1", "stuff2", "stuff3");
    echo implode('<br>', $my_array);
?>
Matt S
  • 14,976
  • 6
  • 57
  • 76
castle
  • 73
  • 3
  • Thank you for the code block! Although it _might_ answer the question, it is not much good without explanation. Could you include some explanation with your answer. From Review. – Joe Jul 21 '17 at 10:13
2

You need to print with <br/> instead of \n because the default PHP mime type is HTML, and you use <br/> to accomplish line breaks in HTML.

For example,

<?php

$my_array = array("stuff1", "stuff2", "stuff3");

echo $my_array[0] . "<br/>";
echo $my_array[1] . "<br/>";
echo $my_array[2] . "<br/>";

?>
Blake
  • 1,691
  • 2
  • 15
  • 23
2

From my PHP textbook:

One mistake often made by new php programmers (especially those from a C background) is to try to break lines of text in their browsers by putting end-of-line characters (“\n”) in the strings they print. To understand why this doesn’t work, you have to distinguish the output of php (which is usually HTML code, ready to be sent over the Internet to a browser program) from the way that output is rendered by the user’s browser. Most browser programs will make their own choices about how to split up lines in HTML text, unless you force a line break with the <BR> tag. End-of-line characters in strings will put line breaks in the HTML source that php sends to your user’s browser (which can still be useful for creating readable HTML source), but they will usually have no effect on the way that text looks in a Web page.

The <br> tag is interpreted correctly by all browsers, whereas the \n will generally only affect the source code and make it more readable.

Alex Kalicki
  • 1,533
  • 9
  • 20
-1

That's because in HTML a line break is <br />, not "\n".

darma
  • 4,687
  • 1
  • 24
  • 25