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?";
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?";
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?
In Fact,
According to http://www.php.net, (http://us2.php.net/manual/en/function.echo.php)
you'll see that it shows both examples. It seems that it's a matter of whatever the programmer feels more comfortable with. Let me know if you find any further information on it though please.
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.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.