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)?

5
  • 4
    they are both valid, but the first example is easier to read in most text editors and hence make changes to later. Commented Jul 12, 2015 at 4:04
  • 3
    You could also wrap your variable in {} - echo "Example {$example}"; Commented Jul 12, 2015 at 4:04
  • 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. Commented Jul 13, 2015 at 0: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. Commented Dec 17, 2018 at 0:43
  • That's a good point. I think its tough to say if one is hands down better than the other. Commented Dec 17, 2018 at 1:05

1 Answer 1

-1

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

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

echo "Example " . $example;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the advice, I suppose Ill start using his method
"his way is proper" --- and the OP's method is not?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.