-3
<?php

$greeting = 'hi';

echo 'hi' $greeting;
?>

I know that the above works when string interpolation is used such as echo "hi $greeting"; but if the code works individually as in echo 'hi' and echo $greeting I don't understand why the I get an error when the code is combined to be echo 'hi' $greeting; as I illustrated above.

Robert
  • 301
  • 5
  • 12
  • 2
    Concatenate your string and variable. – aldrin27 Aug 03 '17 at 01:34
  • I would like to know why it won't work instead of using a concatenation to make it work. – Robert Aug 03 '17 at 01:37
  • @Robert I recommend to do some research on the language and its' syntax. You can't just guess how it's supposed to work. It's the same reason `foo("hi" "hi")` is invalid in any language. – Spencer Wieczorek Aug 03 '17 at 01:40
  • You're trying to echo a string. To add a variable to that echo you need to concatenate. – giolliano sulit Aug 03 '17 at 01:50
  • If you would still go with this you can do that with brackets like echo 'hi {$greeting}'; – aldrin27 Aug 03 '17 at 02:09
  • @aldrin27 Ah! another way to do it!Thanks!! – Robert Aug 03 '17 at 02:16
  • @SpencerWieczorek Thanks! you are right, my tendency as a rookie in this language was to try to make up rules bymyself and wonder why something wouldn't work this way. But just like grammar in English, there are certain rules and its not smart to ask why this doesnt work. – Robert Aug 03 '17 at 02:18

2 Answers2

1

Because that isn't valid code. You need to concatenate the strings if you want to do it like that:

echo 'hi' . $greeting;
Enstage
  • 2,106
  • 13
  • 20
  • Would there be a technical reason though? I understand that concatenation is necessary here but why? – Robert Aug 03 '17 at 01:35
  • Because thats just how PHP works. `echo` is just a PHP function, and by doing `echo 'hi' $greeting;` you are just putting two expressions next to each other and not telling PHP how they interact with each other. – Enstage Aug 03 '17 at 01:37
  • Additionally, `echo` can take multiple strings without concatenation by passing them as separate parameters: `echo 'hi', $greeting;` – Enstage Aug 03 '17 at 01:40
  • Ah! interesting it works when there is a commna between! Thanks!Thanks! – Robert Aug 03 '17 at 01:50
0

You have to replace your code's this part

echo 'hi' $greeting;

to

echo 'hi'.$greeting;
Ahmet Karabulut
  • 153
  • 1
  • 12