13

If I have a variable $var in this string: echo "Hello, there are many $vars";

Php looks for the variable $vars instead of $var.

Without concatenation like: "Hello, there are many $var" . "s";
is there another way to do this, like some sort of escaping character?

0

4 Answers 4

32

In php you can escape variables like so

echo "Hello, ${var}'s head is big";

or like

echo "Hello, {$var}'s head is big";

Reference here under escape character section

Sign up to request clarification or add additional context in comments.

3 Comments

Funny thing, I knew this too, but when I search for a reference in the php documentation, I can't find any. I'm probably searching wrong, so does anyone have it?
And then of course I find it - may be useful for reference: pa2.php.net/manual/en/…
@Joubarc same here, I couldn't find it anywhere in documentation. That's why I asked it here
6

You can use {} to escape your variable properly. Consider the following example:

echo "There are many ${var}s"; #Or...
echo "There are many {$var}s";

Working example

Comments

2

Alternatively you may want to look at sprintf: http://php.net/manual/en/function.sprintf.php

The sprintf function allows you to format any type of variable as a string in a specific notation.

Comments

1

Personally I always divide the variables from a string like this: echo 'Hello, there are many '.$var.'s';

Mostly because of readability, if you go through your code it's instantly clear where the variables are.

7 Comments

Harder than it sounds if there's 3 sets of escaped quotes and 5 variables in 1 string
readability is the exact reason why I prefer the other solution
That actually depends on your IDE/editor. My editor highlights these variables for me, so I always have readable code. Also, using {} to call those variables will give the seam readability effect.
Maybe I should look at different editors, because I'd highly prefer doing it with brackets if it showed up in my editor.
It does for me, and no plugins used. See picasaweb.google.com/lh/photo/… Make sure you are using double quotes though, single quotes don't evaluate variables.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.