Can I echo a variable with single quotes?

Solution 1:

You must either use:

echo 'I love my ' . $variable . '.';

This method appends the variable to the string.

Or you could use:

echo "I love my $variable.";

Notice the double quotes used here!

Solution 2:

If there's a lot of text, have a look at the Heredoc syntax.

$var = <<<EOT
<div style="">Some 'text' {$variable}</div>
EOT;

Solution 3:

The documentation says:

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.

So the answer is no, not in this way.

The solution is simple:

Don't echo HTML.

As long you are not creating like partial views or stuff , there is no reason to echo HTML. Embed PHP into HTML instead:

<div class="foo">
    <span><?php echo $value; ?></span>
</div>

The benefits are:

  • Don't have to remember escaping of quotes.
  • Easier to maintain HTML code.

†: In this case heredoc [docs] is the least worse alternative.

Solution 4:

No. Variables (and special characters) only expand in strings delimited with double quotes. If you want to include a variable in a single-quote delimited string, you have to concatenate it instead:

echo 'I love my '.$variable.'.';

You could also escape the double quotes of your HTML if you'd rather use strings delimited by doble quotes:

echo "<a href=\"$url\">$text</a>";

See the PHP manual on strings, especially the part on string parsing, for more information.

Solution 5:

No. ' will not parse variables. use

echo 'I love my '.$variable.'.';

or

echo "I love my {$variable}. And I have \" some characters escaped";