-2

I often see programmers on Youtube concatenating like: .$example. Small question, I would like to know what the difference is between .$name. and "$name" because they give the same output.

 <?php
 $name = 'Todd';
 echo "Hello $name!";

 echo "Hello " .$name. "!";
 ?> 
Vitalynx
  • 946
  • 1
  • 8
  • 17
  • [PHP - concatenate or directly insert variables in string](http://stackoverflow.com/a/5605970/3110638) – Jonny 5 Dec 25 '13 at 17:25

2 Answers2

1

When you use variables directly in a string literal, it is hard to read. You (usually) lose the benefit of your IDE showing you with different colors what is what. You can see this in the StackOverflow formatting of the code in your question.

If you're just using echo, consider using a list of strings instead:

echo 'Hello ', $name, '!';

No concatenation is needed, and each string is copied to the output buffer. In theory this is faster, but for typical small strings you certainly won't notice any speed difference.

Brad
  • 159,648
  • 54
  • 349
  • 530
0

Yeah both produces the same output.

In the below example, Variables inside the double quotes are interpreted.

$name = 'Todd';
echo "Hello $name!"; // prints "Hello Todd!"

See the same example when you need to show the same using single quotes.

$name = 'Todd';
echo 'Hello $name!'; // prints "Hello $name!"

In the above case , the concatenate operator comes to rescue. So you can echo 'Hello '.$name;// prints "Hello Todd!"

The concatenate operator has its own specialities , i just explained it for your context.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126