Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing a PHP variable with a string literal

People also ask

How do you pass a variable inside a string in PHP?

In PHP, variables can be parsed within strings specified with double quotes ( " ). This means that within the string, the computer will replace an occurence of a variable with that variable's value.

What is literal string in PHP?

PHP string literal A string literal is the notation for representing a string value within the text of a computer program. In PHP, strings can be created with single quotes, double quotes or using the heredoc or the nowdoc syntax.

What is literals and variables in PHP?

When a string is enclosed in single quotes, all characters are treated as literals. Variable substitution will not occur. Single quotes can be nested within double quotes and vice versa. Quotes can be escaped with a backslash to make them literal characters within a string.


echo "{$test}y";

You can use braces to remove ambiguity when interpolating variables directly in strings.

Also, this doesn't work with single quotes. So:

echo '{$test}y';

will output

{$test}y

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.


Example:

$test = "chees";
"${test}y";

It will output:

cheesy

It is exactly what you are looking for.