tags:

views:

94

answers:

3

simple problem baffling me...

i have a function:

function spitHTML() {
    $html = '
    <div>This is my title</div>\n
    <div>This is a second div</div>';

    return $html
}

echo $spitHTML();

Why is this actually spitting out the \n's?

+3  A: 

Change ' to " :) (After that, all special chars and variable be noticed)

$html = "
<div>This is my title</div>\n
<div>This is a second div</div>";
Rin
+4  A: 

Because you're using single quotes - change to double quotes and it will behave as you expect.

See the documentation for Single quoted strings.

RichieHindle
sigh...DUH...i should've tried that. BUT, what is the real difference? I guess i will just post another question haha...thanks!
johnnietheblack
@johnnietheblack, Read the documentation!
strager
+4  A: 

Backslashes used in single quote strings do not work as escape characters (besides for the single quote itself).

$string1 = "\n"; // this is a newline
$string2 = '\n'; // this is a backslash followed by the letter n
$string3 = '\''; // this is a single quote
$string3 = "\""; // this is a double quote

So why use single quotes at all? The answer is simple: If you want to print, for example, HTML code, in which naturally there are a lot of double quotes, wrapping the string in single quotes is much more readable:

$html = '<div class="heading" style="align: center" id="content">';

This is far better than

$html = "<div class=\"heading\" style=\"align: center\" id=\"content\">";

Besides that, since PHP doesn't have to parse the single quote strings for variables and/or escaped characters, it processes these strings a bit faster.

Personally, I always use single quotes and attach newline characters from double quotes. This then looks like

$text = 'This is a standard text with non-processed $vars followed by a newline' . "\n";

But that's just a matter of taste :o)

Cassy
+1 - nice explanation
karim79