Differences in declaring values when echoing back results

Hi All,

I am now pretty comfortable with this, but at first I found the differences in syntax a bit confusing. Below is two different ways of presenting the same thing. Do the experts have a preference and why?

Method #1

echo "<p>Thanks {$_POST[‘name’]}, for your comments:<br />
{$_POST[‘comments’]}</p>
<p>We will reply to {$_POST[‘email’]}.</p>
";

versus

Method #2

$name = $_POST[“name”];
$comments = $_POST[“comments”];
$email = $_POST[“email”];

echo "<p>Thank you, $name, for your comments:<br />
$comments</p>
<p>We will reply to $email.</p>
";

BTW - I have a preference, but only for one reason. By declaring the variables, it helps me think about the structure of my project more clearly. That said, I think I will eventually not have to worry about this and use method #1.

Thanks ahead for any further feedback.

Jim

Using the incoming variable directly as in $_POST[‘name’] makes it very obvious where this var has come from, and in this case also makes it very clear that it is not to be trusted, that it needs escaping and may need filtering.

However it is harder to write and is prone to mistyping, plus it is ugly and hard to read. This befuddles the mind when trying to follow the flow of a script in your head.

$name is easier to read, making it somewhat easier to follow the code. BUT you cannot be sure where it came from, it is a name, but the name of what? Has the variable been checked? is the variable safe to put into my database or output as html?

As a rule of thumb, if I a script is only accessing a POST (or GET) var once I leave it as a $_POST[‘var’];

If it is going to access that POST var twice, i’d tend to still leave it as $_POST;

But any more, or if I thought I’d use it more than twice, then yes, I’d do this:

$name = $_POST[“name”];

This would be especially true if I did any kind of validation or processing on that var.