Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different output from same function with same parameters

I am confused with following string function

echo strlen("l\n2"); //give 3 in output

where as

echo strlen('l\n2'); //give 4 in output

can anybody explain why ?

like image 266
user1458253 Avatar asked Mar 26 '26 15:03

user1458253


2 Answers

Because when you use single quotes (' '), PHP does not expand the \n as a single new line character whereas in double quotes (" "), \n translates to the new line character (ie. a single character) thus giving 3 characters

Taken from PHP's String Documentation: http://php.net/manual/en/language.types.string.php

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

like image 102
Suhail Patel Avatar answered Mar 29 '26 04:03

Suhail Patel


\n is not parsed as a newline character when the string is wrapped in single quotes. Instead, it is treated as a literal \ followed by n.

like image 40
Niet the Dark Absol Avatar answered Mar 29 '26 05:03

Niet the Dark Absol