Echoing New Lines in JavaScript Alert Box Using PHP

May 5th, 2011 - Posted by Steve Marks to Javascript / jQuery, PHP, Web Development.

Alert boxes in JavaScript provide a useful way to show the user an error, message or prompt. Adding new lines to one of these alert boxes can be done like so:

alert("This is line one\nThis is line two");

The above bit of JavaScript would output the following:

Reproducing With PHP

At first glance your initial thought on outputting the above using PHP might be to do something as follows:

echo "alert('This is line one\nThis is line two');";

Go ahead, give it a go and you’ll see that the new line is infact ignored and actually results in an error being generated.

The Solution

Solving this is easier than you might think. Simply add a second backslash before the existing one as shown below:

echo "alert('This is line one\\nThis is line two');";


This entry was posted on Thursday, May 5th, 2011 at 11:06 pm by +Steve Marks and is filed under Javascript / jQuery, PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (2)
  1. Chan says:

    Thanks! I didn’t come up with that idea. LOL :D

  2. David says:

    Thanks, this was helpful.