175

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?

Matt McDonald
  • 4,791
  • 2
  • 34
  • 55
  • 1
    by `$test = cheese;` you meant `$test = 'cheese';` at the end your post (if I am not wrong)... – Outcast Mar 22 '18 at 13:42

5 Answers5

304
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
boroboris
  • 1,548
  • 1
  • 19
  • 32
alex
  • 479,566
  • 201
  • 878
  • 984
  • 2
    is it also possible to inline function calls with such a method? Something similar to `"foo{implode(',', [abc])}bar"` – velop Apr 27 '17 at 15:46
  • 1
    @velop Nope. Building strings is often done after processing has occurred. Calling functions in the middle of preparing your output it often not what you want. Consider calling the function first, storing the result in a variable and then you can include it in the string `echo "like so: $var";`. – Jochem Kuijpers Jul 13 '18 at 01:21
  • how to embed a ternary operator that evaluates to two diff strings in a string? – oldboy Jul 27 '19 at 07:23
59

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • Thanks. I tried reading the strings manual but wasn't sure exactly what I was looking for to search it for what I was after. – Matt McDonald Mar 20 '11 at 14:00
  • 2
    You're welcome :-) Yeah, not always easy to find the right section, when you don't really know what you're searching for ^^ – Pascal MARTIN Mar 20 '11 at 14:01
  • 1
    Worth noting that once you're inside the {}, you can use expressions, not just variable names, such as {$x->y[3]} or whatever. – TextGeek Oct 29 '16 at 15:35
8

Example:

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

It will output:

cheesy

It is exactly what you are looking for.

Catalin Pirvu
  • 175
  • 2
  • 8
Rizwan
  • 89
  • 1
  • 1
1

"${test}y" is deprecated since PHP 8.2, use "{$test}y" instead. (Note the $ being covered by the curly braces.)

legolas108
  • 199
  • 1
  • 5
-2
$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']
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129