Saturday, 8 July 2017

Best Practices: working with long, multiline strings in PHP?


but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?



No one here seemed to actualy answer this question, so here I am.


\r represents 'carriage-return'


\n represents 'line-feed'


The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:


A line feed,\n, means moving to the next line.


A carriage return, \r, means moving the cursor to the beginning of the line.


Ultimately Hello\n\nWorld should result in the following output on the screen:


Hello
World

Where as Hello\r\rWorld should result in the following output.


It's only when combining the 2 characters \r\n that you have the common understanding of knew line. I.E. Hello\r\nWorld should result in:


Hello
World

And of course \n\r would result in the same visual output as \r\n.


Originally computers took \r and \n quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n on its own. It never depends on the OS, but it does depend on what you're viewing the output in.


Still I'd always advise using \r\n wherever you can!

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...