7

I understand that:

'\n' // literally the backslash character followed by the character for lowercase n
"\n" // interpreted by php as the newline character

But for the life of me, I can't understand why '\n' === '\\n'. In my mind, '\\n' would equal three separate characters: two separate backslashes, followed by the letter n.

Why is '\n' === '\\n' true in PHP?

Lion
  • 18,729
  • 22
  • 80
  • 110
JoeCortopassi
  • 5,083
  • 7
  • 37
  • 65
  • 2
    possible duplicate of [In PHP do i need to escape backslashes?](http://stackoverflow.com/questions/3415683/in-php-do-i-need-to-escape-backslashes) and [Difference between single quote and double quote string in php](http://stackoverflow.com/questions/3446216/difference-between-single-quote-and-double-quote-string-in-php) – mario Jul 03 '12 at 00:08

3 Answers3

10

From the manual (section on single quoted strings):

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\). All other instances of backslash will be treated as a literal backslash

so in a single quoted string \n is two characters, but \\n is a literal backslash followed by the letter 'n' - i.e. the same two characters.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
Tim Fountain
  • 33,093
  • 5
  • 41
  • 69
  • Just tried in http://codepad.org/xXixnCG9. Can honestly say that this one made me die a little bit on the inside – JoeCortopassi Jul 03 '12 at 00:03
  • 3
    @joecortopasi: why? single quoted strings don't interpret anything inside them, EXCEPT backslashes so you can insert literal single quotes inside a single-quoted string. – Marc B Jul 03 '12 at 00:08
  • For some reason that hadn't occurred to me. Totally legitimate reason for it :p – JoeCortopassi Jul 03 '12 at 00:13
4

The backslash is still an escape character in single-quoted strings (it escapes literal single quotes).

This is illegal for instance (since the backslash escapes the closing quote):

$path = 'C:\';

So \\ must map to a literal backslash to avoid inadvertent escaping.

Kit Grose
  • 1,792
  • 16
  • 16
  • 3
    +1 for supplying the only legitimate reason to use \\ in a single quoted string. (Before this answer, I actually couldn't think of one). – John V. Jul 03 '12 at 00:08
2

It is because '\\n' is actually \n because the backslash is an escape character that acts strange in single quotes. It doesn't escape n, but does escape \

Cole Tobin
  • 9,206
  • 15
  • 49
  • 74