Jump to content

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>";

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.