1

I had to take a test about php to evaluate my knowledge in the field. One of the questions was to tell, what is the output of echo '{$x}';? Since I've never seen this kind of brackets outside function calls, I had no idea.

What's the answer?

Zoltán Schmidt
  • 1,286
  • 2
  • 28
  • 48
  • 5
    Since you're using single quotes it echo's `{$x}`. – Daan Aug 18 '16 at 11:30
  • 4
    [Check this out](http://stackoverflow.com/questions/2596837/curly-braces-in-string-in-php) – Brett Gregson Aug 18 '16 at 11:30
  • 1
    Also check out the difference between single quoted strings and double quoted strings [PHP Dcs](http://www.php.net/manual/en/language.types.string.php) – Mark Baker Aug 18 '16 at 11:32
  • @CasimiretHippolyte the issue is that in several cases I *lack* the sufficient knowledge. Not that it prevents me from answering, but I definitely need to learn about the syntax. – Zoltán Schmidt Aug 18 '16 at 11:38

2 Answers2

3

It seems like it was a trick question, first to see if you know what curly braces are used for in a PHP string, but also to to see if you know what the difference between double and single quotes in PHP strings, where single quotes are not evaluated and double quotes are, eg:

$name = "bob";
echo "hello $name"; // hello bob
echo 'hello $name'; // hello $name

I'm guessing they were assuming you would see the curly braces, which are used to isolate a variable within a string and give that answer without looking at the quotes:

$place = 3;
echo "you are {$place}rd in the line"; // you are 3rd in the line
echo "you are $placerd in the line"; // error, $placerd is not defined
echo 'you are {$place}rd in the line';  // you are {$place}rd in the line
Brett Gregson
  • 5,867
  • 3
  • 42
  • 60
  • so `"you are {$place}rd in the line"` is equivalent to `"you are".$place."rd in the line"`? – Zoltán Schmidt Aug 18 '16 at 11:43
  • Yeah output will be exactly the same. The curly braces are just used to separate (isolate) the PHP variable within a double quote string, so in the example above to separate the variable (`$place`) from the `"rd"` part of the string – Brett Gregson Aug 18 '16 at 11:47
1

When you use single quotes (') - like in this scenario: echo '{$x}';, The Variable $x is not affected in any way. This means that everything within the single quotes would be interpreted as string and echoed back verbatim. However, if you had used double quotes instead of single quotes like so: echo "{$x}";, this would rather result in the evaluation of the value of $x and the result would be echoed. See the Documentation for more information.

Poiz
  • 7,611
  • 2
  • 15
  • 17