5

I was watching a PHP tutorial and noticed that the teacher was adding varibles to his echo statements in a different way to me. This got me thinking, which way should I be using? Is one more correct than the other?

Here's what the teacher was doing

echo "Example " . $example;

Here's what I do

echo "Example $example";

My method works, but I don't want to get into any bad habits. Could someone please tell me which way I should be using (preferably with some evidence)?

Jonty Morris
  • 797
  • 1
  • 10
  • 25
  • 4
    they are both valid, but the first example is easier to read in most text editors and hence make changes to later. – David Jul 12 '15 at 04:04
  • 3
    You could also wrap your variable in `{}` - `echo "Example {$example}";` – Darren Jul 12 '15 at 04:04
  • Thanks for the advice – Jonty Morris Jul 12 '15 at 04:08
  • _`echo "Example ", $example;`_ also works. note `comma` as the separator rather than a `fullstop` which is the concatenation operator. It is useful when dealing with strings which use the different types of qoute characters in a string. – Ryan Vincent Jul 13 '15 at 00:06
  • 1
    I think that the second version is more readable and less error prone, especially if you have more than one variable to concatenate. – tonethar Dec 17 '18 at 00:43
  • That's a good point. I think its tough to say if one is hands down better than the other. – Jonty Morris Dec 17 '18 at 01:05

1 Answers1

-1

According to the PHP.NET documentation, his way is proper.

http://php.net/manual/en/language.operators.string.php

echo "Example " . $example;
Darren
  • 13,050
  • 4
  • 41
  • 79
M H
  • 2,179
  • 25
  • 50