skip to Main Content

The phone number in a form isn’t required. I would like to hide the label if the phone number field didn’t collect any data.

Something like this in theory?

$mail->Body = "
  <p><strong>Name: </strong> $full_name</p> 
  <p><strong>Email: </strong> $email</p>". 
  if ($phone !== ''){
    echo '<p><strong>Phone: </strong> $phone</p>';
  } else {
    echo '';
  } . "
  <p><strong>Message: </strong> $message</p> 
";

But is not the right syntax. How can I do this? p.s. a Ternary expression would even be cleaner, but it didn’t work either

3

Answers


  1. Don’t echo, append content:

    $mail->Body = "<p><strong>Name: </strong> $full_name</p> 
      <p><strong>Email: </strong> $email</p>";
     
      if ($phone !== ''){
        $mail->Body .= '<p><strong>Phone: </strong> $phone</p>';
      }
    
      $mail->Body .= '<p><strong>Message: </strong> $message</p>';
    
    Login or Signup to reply.
  2. Another alternative, which works better in some situations:

    if( $phone )
        $phone = "<p><strong>Phone: </strong>$phone</p>";
    $mail->Body = "<p><strong>Name: </strong>$full_name</p> 
      <p><strong>Email: </strong>$email</p>
      $phone
      <p><strong>Message: </strong>$message</p>";
    
    Login or Signup to reply.
  3. $string = "
      <p><strong>Name: </strong> $full_name</p> 
      <p><strong>Email: </strong> $email</p>". 
      ($phone !== '' ? '<p><strong>Phone: </strong> $phone</p>' : '').
    "<p><strong>Message: </strong> $message</p>";
    $mail->Body = $string;
    

    This is easier. Make the string first then append the string to the body of the mail.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search