if statement inside email $MESSAGE_BODY

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
DedMousie
Forum Newbie
Posts: 12
Joined: Sat Feb 12, 2011 7:21 pm

if statement inside email $MESSAGE_BODY

Post by DedMousie »

I'm using the standard (?) method to send email from a rather complicated form:
mail($to, $subject, $MESSAGE_BODY, $headers);

It's almost working exactly as I want - however, if certain form fields weren't used, I don't want to display them in the email.

So, here's what I've got on my normal page:

<?php if ($primary_tc_travdates == 'yes'): ?>
<strong>Depart Date:</strong> $tc_depdate - <strong>Return Date:</strong> $tc_retdate
<?php endif ?>

How do I translate this over into my $MESSAGE_BODY?

All other variables like the below are working as expected:
<p><strong>$prim_fname $prim_lname</strong> <br />
Phone: $prim_phone <br />
Email: $prim_email <br />
Date of Birth: $prim_dob</p>
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: if statement inside email $MESSAGE_BODY

Post by Jonah Bron »

Then do it like this:

Code: Select all

$MESSAGE_BODY = "<p><strong>$prim_fname $prim_lname</strong>";

if ($prim_phone) {
    $MESSAGE_BODY .= "\n\nPhone: $prim_phone";
}
if ($prim_email) {
    $MESSAGE_BODY .= "\n\nEmail: $prim_email";
}
if ($prim_dob) {
    $MESSAGE_BODY .= "\n\nDate of Birth: $prim_dob";
}

$MESSAGE_BODY .= '</p>';
That code will go through each field, and only add it to the message if it's not empty.
Post Reply