Search code examples
phpphpmailer

Don't display message text if field is empty in phpmailer


I am working on a form using phpmailer. Here is the basic expression to display one of the fields:

 $f_request = isset($_POST['f_request']) ? htmlspecialchars($_POST['f_request']): "";

$msgBody .= "

■Text1

$f_request

"

How can I display "■Text1", only if $f_request is not empty?

Sorry, my PHP knowledge is really low, so I don't know the correct grammar to build an if condition.


Solution

  • You're already checking isset(), but you'll additionally probably want to confirm it's not empty with !empty(). You don't need to make use of $f_request at all, as your check can be against the $_POST itself. You can also conditionally append it to the $msgBody if it's set, as can be seen in the following:

    $msgBody = "";
    if (isset($_POST['f_request']) && !empty($_POST['f_request'])) {
        $msgBody .= "■Text1" . $_POST['f_request'];
    }