Joining 2 Variables

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Joining 2 Variables

Post by donny »

Hello

I have 2 variables that I want to join together.

$a = hello
$b = world

a + b = c
$c= hello world

i need to have a space between the variables i am joining.

thank you so much
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Joining 2 Variables

Post by requinix »

What have you tried?
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Joining 2 Variables

Post by donny »

I used implode()

Code: Select all

$firstmiddle = implode(',', array($first_name,$middle_name));

is there anyway that if $middle_name is null that $firstmiddle becomes = to $first_name and no comma is added?


i also please need help with joining 3 variables together and adding a comma after the first one
example
$fulladdress = $town,$state $zip

i want a comma to be placed between $town and $state and only a space between $state and $zip

thank you!!!!
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Joining 2 Variables

Post by Celauran »

Simplest answer is to just use the concatenation operator: .

Code: Select all

$fullname = $first_name . " " . $last_name;
$address = $city . ", " . $state . " " . $zip;
You can also evaluate variables inside double quoted strings, so

Code: Select all

$fullname = "{$first_name} {$last_name}";
$address = "{$city}, {$state} {$zip}";
is equivalent to the examples above.
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Joining 2 Variables

Post by donny »

thank you

i am trying to make $firstmiddle = $firstname,$middlename with a comma separating

however if there is no middle name i want $firstmiddle = $firstname without a comma

this is what I'm trying now it doesn't seem to be working

Code: Select all

if (empty($middle_name)) {
    $firstmiddle = $first_name;
} elseif (isset($middle_name)) {
    $firstmiddle = $firstname . ", " . $middlename;
}
i really appreciate all your help thanks for your patience
donny
Forum Contributor
Posts: 179
Joined: Mon Aug 11, 2014 11:18 am

Re: Joining 2 Variables

Post by donny »

i fixed it thank you very much i had variables wrong


thanks for your help
Post Reply