Jump to content

If statement in the middle of string concatenation?


brian914

Recommended Posts

I am trying to figure out how to have an if statement in the middle of strings I am trying to concatenate. I have a from that has a address1 and address2, where address2 often does not exist. So I want to only add that line if there is actually content. I was trying something like the following, but that is giving me an error. I am pretty new to php, so I can't seem figure it out. Any help would be greatly appreciated.

 

"<p><strong>Address 1: </strong><br>" . $address1 . "<br>"
if ( isset($address2) ) { echo . $address2 . "<br>" }
. $city . ", " . $state . " " . $zip . "</p>"

You can keep concatenating the address to itself based the condition like this:

$address = "
Address 1: 
" . $address1 . "
";
if (isset($address2))
{ 
   $address .= $address2 . "
";
}
$address .= $city . ", " . $state . " " . $zip . "";

or you can use the ternary operator

 

$address = "<p><strong>Address 1: </strong><br>" . $address1 . "<br>" .
            (isset($address2) ? $address2 . "<br>" : '') .
            $city . ", " . $state . " " . $zip . "</p>";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.