176

I don't actually know how to describe what I wanted, but I'll show you:

For example:

$data1 = "the color is";
$data2 = "red";

What should I do (or process) so $result is the combination of $data1 and $data2?

Desired result:

$result = "the color is red";
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
glennanyway
  • 1,803
  • 2
  • 12
  • 3
  • 1
    There are a lots of way to do it. if you see the answer you can check it out that. but use the simplest one. for example $result="$data1 $data2"; that's it. or $result=$data1.$data2; – jewelhuq Jan 13 '16 at 10:11
  • 1
    @Machavity can you magically raise the protection level so that redundant posts don't keep piling up on this page? – mickmackusa Jul 06 '18 at 02:02
  • 2
    I think the above criticisms that OP has asked an overly basic question are part of the reason why SO has attained a reputation of being such a hostile and unfriendly place for beginners to go to. I think it's a perfectly valid question for the site. However, I do take issue with the fact that OP hasn't accepted a very detailed and useful answer in nine years. Don't forget about the tick button OP! – Lou Sep 01 '20 at 15:21

17 Answers17

256
$result = $data1 . $data2;

This is called string concatenation. Your example lacks a space though, so for that specifically, you would need:

$result = $data1 . ' ' . $data2;
Logan Serman
  • 28,585
  • 25
  • 101
  • 141
116

There are several ways to concatenate two strings together.

Use the concatenation operator . (and .=)

In PHP . is the concatenation operator which returns the concatenation of its right and left arguments

$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;

If you want to append a string to another string you would use the .= operator:

$data1 = "the color is ";
$data1 .= "red"

Complex (curly) syntax / double quotes strings

In PHP variables contained in double quoted strings are interpolated (i.e. their values are "swapped out" for the variable). This means you can place the variables in place of the strings and just put a space in between them. The curly braces make it clear where the variables are.

$result = "{$data1} {$data2}";

Note: this will also work without the braces in your case:

$result = "$data1 $data2";

You can also concatenate array values inside a string :

$arr1 = ['val' => 'This is a'];
$arr2 = ['val' => 'test'];
$variable = "{$arr1['val']} {$arr2['val']}";

Use sprintf() or printf()

sprintf() allows us to format strings using powerful formatting options. It is overkill for such simple concatenation but it handy when you have a complex string and/or want to do some formatting of the data as well.

$result = sprintf("%s %s", $data1, $data2);

printf() does the same thing but will immediately display the output.

printf("%s %s", $data1, $data2);
// same as
$result = sprintf("%s %s", $data1, $data2);
echo $result;

Heredoc

Heredocs can also be used to combine variables into a string.

$result= <<<EOT
$data1 $data2
EOT;

Use a , with echo()

This only works when echoing out content and not assigning to a variable. But you can use a comma to separate a list of expressions for PHP to echo out and use a string with one blank space as one of those expressions:

echo $data1, ' ', $data2;
Alexandre Elshobokshy
  • 10,357
  • 6
  • 25
  • 53
John Conde
  • 212,985
  • 98
  • 444
  • 485
28

Another possibility is the .= operator. I'm using it for huge SQL queries.

$string = "the color is ";
$string .= "red";

echo $string; // Gives: the color is red
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
codelame
  • 497
  • 4
  • 13
  • "I'm using it for huge sql queries." - note that it is a typical way of getting https://en.wikipedia.org/wiki/SQL_injection – reducing activity Jul 17 '19 at 07:03
  • how exactly concatenating string this or other way will give me sql injection in my parameterized query? – codelame Sep 05 '19 at 22:27
  • 1
    Manually building entire SQL queries (at least suggested by "for huge sql queries") is not OK. Preparing just parameters, not entire queries should be safe from this specific security risk. – reducing activity Sep 15 '19 at 11:53
20

Concatenate them with the . operator:

$result = $data1 . " " . $data2;

Or use string interpolation:

$result = "$data1 $data2";
Paige Ruten
  • 165,471
  • 36
  • 174
  • 194
13
$result = implode(' ', array($data1, $data2));

is more generic.

  • 1
    this is very useful in a case where you want to make a delimited list as it checks if the vars have any values `$email_to = implode(', ', array($addr1, $addr2, addr3));` no need for `if($addr != '')` etc – Aba Jan 05 '16 at 17:12
  • 4
    Don't choose array functions, unless you must. Because array functions allways slower than operators. Additionally; they use more ram. – MERT DOĞAN Oct 20 '16 at 14:28
10

Another form available is this:

<?php
$data1 = "the color is";
$data2 = "red";
$result = "{$data1} {$data2}";
Tim G
  • 1,784
  • 11
  • 25
7

You can do this using PHP:

$txt1 = "the color is";
$txt2 = " red!";
echo $txt1 . $txt2;

This will combine two strings and the output will be: "the color is red!".

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
sunil
  • 781
  • 13
  • 25
  • 1
    Your fabricated input values do not represent the OP's input string and you are echoing solutions that have been stated YEARS earlier. This is not a javascript question so that advice is irrelevant. This post adds no value to the page. – mickmackusa Jul 06 '18 at 01:55
  • @mickmackusa, ok I updated text, you are right but I gave js answer here because this is a very basic question so the user can learn the difference – sunil Jul 06 '18 at 11:28
  • 1
    Your update is NOT using the OP's text. Do not provide javascript solutions to php questions. This answer is poorly formatted and adds no value to the page. – mickmackusa Jul 06 '18 at 11:48
6

You can try the following line of code

$result = $data1 . " " . $data2;
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
user710502
  • 10,711
  • 27
  • 102
  • 161
  • I would rather use single quotes instead of double quotes. [link](https://stackoverflow.com/questions/3446216/what-is-the-difference-between-single-quoted-and-double-quoted-strings-in-php) – Jack Mar 02 '19 at 00:33
5

A period is used to concatenate strings. Simple example to turn two string variables into a single variable:

$full = $part1 . $part2;

In your example, you'd want to do:

$result = $data1 . ' ' . $data2;

You'll notice I added a string of one space between the two variables. This is because your original $data1 did not end with a space. If you had combined them without it, your $result variable would end up looking like the color isred.

Aken Roberts
  • 12,492
  • 3
  • 33
  • 40
4

This should work for you:

$result = $data1 . " " . $data2;` 

Reference: PHP String Variables

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Robert
  • 3,066
  • 3
  • 23
  • 32
3
$s = "my name is ";

$s .= "keyur";

echo $s; 

result:

my name is keyur
Johannes
  • 59,058
  • 16
  • 59
  • 114
keyur sojitra
  • 163
  • 1
  • 4
  • 9
    Welcome to StackOverflow. It is nice, if you answer questions. However, if you do, please format it propertly. Further, your answer was already given. How does it add additional value to this *four year old* post? – T3 H40 Mar 22 '16 at 13:35
  • 6
    This is just a repeat of the existing answers. – Pang Sep 22 '16 at 00:48
3

Try this:

$result = $data1 . $data2;
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Farhan
  • 422
  • 6
  • 13
  • 6
    This isn't correct answer. it results "the color isred". Also, your answer is duplicated from someone's answer posted years ago. Down voted. – Jason Liu Aug 24 '18 at 21:03
3

I am not exactly clear with what your requirements are, but basically you could separately define the two variables and thereafter combine them together.

$data1="The colour is ";
$data2="red";

$result=$data1.$data2;

By doing so you can even declare $data2 as a global level, so you could change its value during execution. For instance, it could obtain the answer "red" from a checkbox.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Yoosuf
  • 882
  • 6
  • 32
  • 52
0

Combine two strings together in PHP:

$result = $data1 . ' ' . $data2;
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
  • 3
    This answer offers nothing the other answers haven't already provided and offers no explanation as to why or how this works. – John Conde Aug 23 '19 at 20:33
-1

I believe the most performant way is:

$data1 = "the color is";
$data2 = "red";
$result = $data1 . ' ' . $data2;

If you want to implement localisation, you may do something like this:

$translationText = "the color is %s";
$translationRed  = "red";
$result = sprintf($translationText, $translationRed);

It's a bit slower, but it does not assume grammar rules.

Pedro Amaral Couto
  • 1,418
  • 11
  • 11
-2
  1. Concatenate the string (space between each string)

    Code Snippet:

    <?php
        $txt1 = "Sachin";
        $txt2 = "Tendulkar";
    
        $result = $txt1 . $txt2 ;
        echo $result . "\n";
    ?>
    

    Output: SachinTendulkar

  2. Concatenate the string where space exists

    Code Snippet:

     <?php
         $txt1 = "Sachin";
         $txt2 = "Tendulkar";
    
         $result = $txt1 . " " . $txt2;
         echo $result . "\n";
     ?>
    

    Output: Sachin Tendulkar

  3. Concatenate the string using printf function.

    Code Snippet:

     <?php
         $data1 = "Sachin";
         $data2 = "Tendulkar";
         printf("%s%s\n", $data1, $data2);
         printf("%s %s\n", $data1, $data2);
     ?>
    

    Output:

     SachinTendulkar
     Sachin Tendulkar
    
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
rashedcs
  • 3,209
  • 2
  • 35
  • 39
-4

Try this. We can append a string in PHP with the dot (.) symbol

$data1 = "the color is";
$data2 = "red";

echo $data1 . $data2; // The color isred
echo $data1 . " " . $data2; // The color is red (we have appended space)
Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124