Which of the following is the proper syntax for the latest version of PHP?

echo "My name is $name. How are you?";
echo "My name is " . $name . ". How are you?";

Recommended Answers

All 6 Replies

I'm not 100% Sure that one form is "more proper" than the other. I do realize that one form is more readable.... but I don't know if one is better syntax than the other?

they both work just fine, HOWEVER if you are referencing an array with a named term such as the following example neither one of these two will work:

echo "my name is $person and my last name is $person ";
echo "my name is $person["f_name"] and my last name is $person["l_name"] ";

so you would be forced to explicitly state that you are citing a variable as in
echo "my name is ".$person." and my last name is ".$person;

Often, arrays will work without any quotes at all ... $myarray[foo]. This is probably a long shot, but can you use double quotes for an array row by escaping them? i.e. $myarray[\"foo\"] ?? I doubt that ;)

I think the use of quotes and escaping the variable within echos is for the sake of exclusivity. In the case of variables containing escaping characters or handling secure connections, you can have problems. Although for the majority of tasks (as the examples show) exclusivity isnt really required.
I guess it depends on what you are doing with the arrays and the strings within them really. each to its own task to be honest.
If you want to dig a hole....

I usually surround variables in "'s with { and }, thus:

echo "This is a {$variable}."

This helps it work out array indeces and stuff, and tends to make it easier to read. As for which format, it usually depends on the context, I use both. Constants don't appear to be translated when in "'s, so you need the latter format in this case.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.