This is something that has been on my “unsure” list for a long time. Partly because I haven’t really done my research on it and because, well, I just don’t require this very often. Finally, today I had a situation come up when I needed to ensure that the notes I am adding into the database are broken up with a line break between each note.
I know that there are these “\n” and “\r” or something like that but any time I’ve tried using them in the past it never worked consistently.
So today I decided to, once and for all, get to the bottom of this.
What I was doing wrong is not always placing the string in double-quotes. Sometimes I had it in single quotes and this is when \n did not work.
$string = "this is my string\n";
$string .= "and this is the next line";
this is my string
and this is the next line
Make sure to use double-quotes (“) not single (‘).
WHEN PASSING STRINGS AROUND IN PHP VARIABLES OR ARRAYS
When you pass this string around from variable to variable or array, they get passed in single quotes, so the \n breaks. To solve that you just need to reset this at the very last pass, like this:
$str = str_replace('\n', "\n", $str);
This will reset the line breaks back in double-quotes. :)