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?

dukevin
  • 22,384
  • 36
  • 82
  • 111

4 Answers4

31

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

Tristan
  • 3,845
  • 5
  • 35
  • 58
  • 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? – Joubarc Aug 12 '11 at 07:47
  • 1
    And then of course I find it - may be useful for reference: http://pa2.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex – Joubarc Aug 12 '11 at 07:48
  • @Joubarc same here, I couldn't find it anywhere in documentation. That's why I asked it here – dukevin Aug 12 '11 at 07:49
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

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
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.

Pelshoff
  • 1,464
  • 10
  • 13
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.

Kokos
  • 9,051
  • 5
  • 27
  • 44
  • Harder than it sounds if there's 3 sets of escaped quotes and 5 variables in 1 string – dukevin Aug 12 '11 at 07:41
  • readability is the exact reason why I prefer the other solution – Serge Wautier Aug 12 '11 at 07:46
  • 1
    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. – Madara's Ghost Aug 12 '11 at 07:48
  • Maybe I should look at different editors, because I'd highly prefer doing it with brackets if it showed up in my editor. – Kokos Aug 12 '11 at 07:54
  • @Rikudo, I downloaded the trial and I'm liking it so far. However it doesn't color code the `{$var}` syntax for me, should I download a plugin for that or something? – Kokos Aug 12 '11 at 09:36
  • 1
    It does for me, and no plugins used. See https://picasaweb.google.com/lh/photo/sSqFtT6OLkT30oNfWANrOlBAFPbq3mohJ6Dj_JvF0H4?feat=directlink Make sure you are using double quotes though, single quotes don't evaluate variables. – Madara's Ghost Aug 12 '11 at 09:41
  • Woops, I've always used single-quotes so didn't stop to think about that. Cheers! – Kokos Aug 12 '11 at 09:43