brian914 Posted March 16, 2012 Share Posted March 16, 2012 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>" Link to comment https://forums.phpfreaks.com/topic/259078-if-statement-in-the-middle-of-string-concatenation/ Share on other sites More sharing options...
Maq Posted March 16, 2012 Share Posted March 16, 2012 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 . ""; Link to comment https://forums.phpfreaks.com/topic/259078-if-statement-in-the-middle-of-string-concatenation/#findComment-1328220 Share on other sites More sharing options...
brian914 Posted March 16, 2012 Author Share Posted March 16, 2012 Thank you very much! Link to comment https://forums.phpfreaks.com/topic/259078-if-statement-in-the-middle-of-string-concatenation/#findComment-1328245 Share on other sites More sharing options...
DavidAM Posted March 16, 2012 Share Posted March 16, 2012 or you can use the ternary operator $address = "<p><strong>Address 1: </strong><br>" . $address1 . "<br>" . (isset($address2) ? $address2 . "<br>" : '') . $city . ", " . $state . " " . $zip . "</p>"; Link to comment https://forums.phpfreaks.com/topic/259078-if-statement-in-the-middle-of-string-concatenation/#findComment-1328256 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.