How do I use single quotes inside single quotes?

Variable expansion doesn't work inside of single quotes. You can do either:

echo "<div id=\"panel1-under\">Welcome {$_SESSION['username']}</div>";

or

echo '<div id="panel1-under">Welcome ' . $_SESSION['username'] . '</div>';

You need to concatenate your strings & variables.

echo '<div id="panel1-under">Welcome ' . $_SESSION['username'] . '</div>';

echo "<div id=\"panel1-under\">Welcome ".$_SESSION['username']."</div>";

or

echo '<div id="panel1-under">Welcome '.$_SESSION['username'].'</div>';

Quick Explain :

  • You don't have to reopen the tags inside a echo String (" ... ")
  • What I have done here is to pass the string "Welcome " concatenated to $_SESSION['username'] and "" (what the . operator does)
  • PHP is even smart enough to detect variables inside a PHP string and evaluate them :

    $variablename = "Andrew";

    echo "Hello $variablename, welcome ";

=> Hello Andrew, welcome

More infos : PHP.net - echo


Inside single quotes, variable names aren't parsed like they are inside double-quotes. If you want to use single-quoted strings here, you'll need to use the string concatenation operator, .:

echo '<div id="panel1-under">Welcome <?php echo "'.$_SESSION['username'].'"; ?></div>';

By the way: the answer to the question in the title is that in order to use a literal single-quote inside a single-quoted string, you escape the single-quote using a backslash:

echo 'Here is a single-quote: \'';

Tags:

Html

Php

Quotes