If within PHP Field

Asked

Viewed 240 times

1

Good Afternoon,

How to Make 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 I would like it to appear only the field ($email, $Whatsapp) if it is different from empty.

  • Make the IF separate, within other variables, and put only the result.

  • The simplest is not to do this. You can concatenate the desired value with the variable within the if, but if you want, you can use the ternary operator.

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 exit would be:

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

Although you can use the ternary operator, but 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 on Ideone.

The exit would be exactly the same:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.