Mixing a PHP variable with a string literal

PhpStringVariables

Php Problem Overview


Say I have a variable $test and it's defined as: $test = 'cheese'

I want to output cheesey, which I can do like this:

echo $test . 'y'

But I would prefer to simplify the code to something more like this (which wouldn't work):

echo "$testy"

Is there a way to have the y be treated as though it were separate from the variable?

Php Solutions


Solution 1 - Php

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

Solution 2 - Php

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.

Solution 3 - Php

Example:

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

It will output:

> cheesy

It is exactly what you are looking for.

Solution 4 - Php

$bucket = '$node->' . $fieldname . "['und'][0]['value'] = " . '$form_state' . "['values']['" . $fieldname . "']";

print $bucket;

yields:

$node->mindd_2_study_status['und'][0]['value'] = $form_state['values']
['mindd_2_study_status']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt McDonaldView Question on Stackoverflow
Solution 1 - PhpalexView Answer on Stackoverflow
Solution 2 - PhpPascal MARTINView Answer on Stackoverflow
Solution 3 - PhpRizwanView Answer on Stackoverflow
Solution 4 - PhpearlyburgView Answer on Stackoverflow