1

I have question because i think i doing unnecessary job.

e.g.

$phone = "222-333-444"
echo "Phone number is " . $phone;

$phone['2'] = "222-333-444"
echo "Phone number is " . $phone['2'];

Please explain is there ANY ANY ANY reason to do it the way above rather than"

$phone = "222-333-444"
echo "Phone number is $phone";

$phone['2'] = "222-333-444"
echo "Phone number is $phone['2']";
3
  • The latter one (with the array) won't work. You will need to use echo "Phone number is {$phone['2']}"; Commented Sep 27, 2011 at 0:51
  • Full Disclosure I don't like PHP: For me it's less readable. I'm likely to skip over it when reading the code. Assuming it's just a string. Commented Sep 27, 2011 at 0:52
  • FYE: The first is "concatenation", the second "interpolation". Commented Sep 27, 2011 at 7:22

5 Answers 5

1

Both are right ways to print a variable. There's no right or wrong, just different approaches.

Sign up to request clarification or add additional context in comments.

Comments

1

No, actually both are equivalent. I personally always write this, because for me it is far more explicit:

echo "Phone number is " . $phone['2'];

Comments

1

The only reason would be consistency and clarity. Concatenation is faster than interpolation, but the difference is so negligible it should not define your choice. I prefer the second personally.

Comments

0

No, there is not difference.

second example should be like this:

$phone = "222-333-444"
echo "Phone number is {$phone}";

$phone['2'] = "222-333-444"
echo "Phone number is {$phone['2']}";

5 Comments

{} are only necessary when the variable is an array and you want to specify an index. For plain variables, {} are optional.
@Kolink: I think, {} notation is always better to prevent mistakes.
Or if you can't use a space: I like $somevars vs I like {$somevar}s
what if its constant will it work with echo "this is {CONSTANT}";?
@MrSchmittt no, according to manual, you have to use echo "this is".constant("CONSTANT"); or echo "this is ".CONSTANT; php.net/manual/en/function.constant.php
-1

No, there is no reason at all, unless your variable is an array and you need to access a specific index.

1 Comment

You can access a specific index both ways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.