[php] How to combine two strings together in PHP?

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

This question is related to php string variables combinations

The answer is


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.


$result = implode(' ', array($data1, $data2));

is more generic.


You can do this using PHP:

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

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


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

  1. 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


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.


$result = $data1 . $data2;

try this


combine two strings together in PHP?

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

$result = $data1 . $data2;

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

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

No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :)

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

echo $string; // gives: the color is red

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;

$s = "my name is ";

$s .= "keyur";

echo $s; 

result:

my name is keyur

Another form available is this:

<?php
$data1 = "the color is";
$data2 = "red";
$result = "{$data1} {$data2}";

I am not exactly clear with what your requirements are but basically you could seperately 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.


This should work for you:

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

Reference: PHP String Variables


Try this , we can append string in php with 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)

Concatenate them with the . operator:

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

Or use string interpolation:

$result = "$data1 $data2";

You can try the following line of code

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

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to combinations

Creating all possible k combinations of n items in C++ Generating combinations in c++ How to combine two strings together in PHP? How to calculate combination and permutation in R? Finding all possible combinations of numbers to reach a given sum Statistics: combinations in Python All combinations of a list of lists How to get all possible combinations of a list’s elements? Algorithm to return all combinations of k elements from n