Your could should work but I don't see the link between processing the form variables at the beginning and the mailing code.
You might need to provide more information as to what you are wanting to do. The nature of your logic will determine the logic required in your code.
Just to clarify: If you know what the names of the POST variables will be you don't need the foreach loop. But (if I've understood you correctly) your form is dynamic and you don't know what the names of the variables will be, in which case the best thing to do is to use a foreach() loop.
If you DO know all the possible variable names, just that some might not be present, you can do it differently, like this:
$use_name = "";
if (isset($_POST["FirstName"])) {
$use_name = $_POST["FirstName"];
if (isset($_POST["LastName"])) {
$use_name .= " ".$_POST["LastName"];
}
}
elseif (isset($_POST["Title"]) || isset($_POST["LastName"])) {
$use_name = $_POST["Title"]." ".$_POST["LastName"];
}
else {
$use_name = "Customer";
}
and later in your code when you send the email:
$email_message = "Dear ".$use_uame.",\nThank you for signing up to our newsletter....";
// more code to determine the rest of $email_message
if (!mail($email_to,$email_subject,$email_message,$email_headers)) {
echo "An error occurred!";
}
else {
echo "We have sent you a welcome email.";
}
The two pieces of code determine how to write the greeting line of an email. It will produce:
Dear John Smith (if both names are available)
Dear John (if only the first name is available)
Dear Mr Smith (if the title and last name are both available)
Dear Subscriber (in other cases)
This example doesn't need foreach() because we know all the possible variable names, even though not all variables might be present.
But if you have no idea what the variable names will be (or can be) then you'll need foreach().
For example, suppose (for some strange reason) your form sends variables beginning with "productID_", for example "productID_00382", "productID_01882", "productID_00724", etc. You have no idea what the variables will be because you have so many product IDs and they can change as you add new products to your catalogue then you'd have to do something like this:
foreach($_POST as $name => $value) {
if (substr($name,0,10) == "productID_" {
// code to handle the many productID_xxx variables
}
}
Having said that, there's a better way to pass such variables, but I was just trying to think of an example where you'd have completely dynamic variable names.
As mentioned before, you should give us more detail because we're kind of guessing the situation and what you want to do.