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?

1
  • 1
    by $test = cheese; you meant $test = 'cheese'; at the end your post (if I am not wrong)...
    – Outcast
    Mar 22, 2018 at 13:42

5 Answers 5

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
3
  • 2
    is it also possible to inline function calls with such a method? Something similar to "foo{implode(',', [abc])}bar"
    – velop
    Apr 27, 2017 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";. Jul 13, 2018 at 1:21
  • how to embed a ternary operator that evaluates to two diff strings in a string?
    – oldboy
    Jul 27, 2019 at 7: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.

3
  • 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. Mar 20, 2011 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 ^^ Mar 20, 2011 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, 2016 at 15:35
8

Example:

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

It will output:

cheesy

It is exactly what you are looking for.

-1

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

-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']

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.