If within PHP Field

1

Good afternoon,

How to do an if within variable value assignment.

$html ='
          <body>
          <table width="100%" style="background:#00aeef;">
          <tr><td>
          <table width="596" border="0" align="center" cellpadding="0" cellspacing="0" style="font-family:Arial;background:#FFF;">
            <tr>
              <td height="78" colspan="2"><img name="index_r1_c1" src="email/img/index_r1_c1.png" width="595" height="78" id="index_r1_c1" alt="" /></td>
            </tr>
            <tr>
              <td height="200" colspan="2" valign="top" style="font-size:16px;padding:30px 15px;font-family:Arial;"><h3>Olá,</h3>
             <h3>     O Cliente abaixo se interessou por um de seus itens publicados no jornal, seguem os dados dele:</h3> 
             <strong>Nome</strong>: '.$nome.'<br>'.
             if($email != ""){
                <strong>E-Mail</strong>: '.$email.'<br>;
                }

             if($whatsapp != ""){
                <strong>WhatsApp</strong>: '.$whatsapp.'<br>;
                }.'
             <h3>Segue abaixo informações sobre o imóvel:</h3>

In case $ html is mounting the body of an email and would like only the field ($ email, $ whatsapp) to appear if it is different from empty.

    
asked by anonymous 18.07.2017 / 19:51

1 answer

0

The simplest is to concatenate the values within the desired conditions:

$email = "[email protected]";
$whatsapp = "";

$html = "<h1>Aqui começa seu HTML</h1>";

if ($email != "") {
    $html .= "<strong>E-mail: {$email}</strong>";
}

if ($whatsapp != "") {
    $html .= "<strong>WhatsApp: {$whatsapp}</strong>";
}

echo $html;
  

See working on Ideone .

The output would be:

<h1>Aqui começa seu HTML</h1>
<strong>E-mail: [email protected]</strong>

Although you can use the ternary operator, this makes it very difficult to read the code:

$email = "[email protected]";
$whatsapp = "";

$html = "<h1>Aqui começa seu HTML</h1>" .
        (($email != "") ? "<strong>E-mail: {$email}</strong>" : "") .
        (($whatsapp != "") ? "<strong>WhatsApp: {$whatsapp}</strong>" : "");

echo $html;
  

See working at Ideone .

The output would be exactly the same:

<h1>Aqui começa seu HTML</h1>
<strong>E-mail: [email protected]</strong>
    
18.07.2017 / 19:59