0

Say you have this array with the following inputs:

$relations["fname"] = 'firstname';
$relations["lname"] = 'lastname';

Now I would like to input the two above values into the following (I know the syntax is incorrect but I would like the firstname and lastname strings to become one string and input into the secondarray):

$secondarray["name"] = $relations["fname"] + $relations["lname"];
2
  • 3
    The string concatenation operator is .. Commented May 6, 2013 at 18:22
  • @deceze that's an answer not a comment Commented May 6, 2013 at 18:42

2 Answers 2

6
$secondarray["name"] = $relations["fname"] + $relations["lname"];

Should be

$secondarray["name"] = $relations["fname"] . $relations["lname"];

The + operator is not overloaded to concatenate strings in PHP.

Sign up to request clarification or add additional context in comments.

3 Comments

That would give you "firstnamelastname" instead of "firstname lastname".
Thanks perfect! Thanks for the explanation about the + operator!
@vascowhite yes you are right but you can do it like this $rel["fname"].' '.$rel["lname"]
5

just for the heck of it :-)

$relations["fname"] = 'firstname';
$relations["lname"] = 'lastname';
$secondarray["name"] = implode($relations," ");

4 Comments

Only if there isn't also $relations["mname"] or $relations["suffix"] or $relations["mphone"] in there somewhere, as well.
Thanks I am sure that would work as well, I have more than just the fname and lname in that array though so it would add everything to it I am sure and probably not what I want...Is this better than using . though?
@user1748026: It was just meant to illustrate that while strings are concatenated using . operator in PHP, if you do have an array with multiple values that you need to convert into a string, you can use the implode function. It might not be very useful for your current use-case. But if you just consider the title of your question, it will make sense. And hey who knows? next time you have a lengthy array to convert you can use this function instead of all those concatenations :)
Thank you very much for the explanation as I might use it in the future!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.