$data1 = "the màu sắc is";$data2 = "red";What should I vì (or process) so $result is the combination of $data1 and $data2?
$result = "the màu sắc is red";
$result = $data1 . $data2;This is called string concatenation. Your example lacks a space though, so for that specifically, you would need:
$result = $data1 . " " . $data2;
There are several ways to lớn concatenate two strings together.
Bạn đang xem: String concatenation in php
Use the concatenation operator . (and .=)
In PHP . Is the concatenation operator which returns the concatenation of its right và 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 màu sắc 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 & 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 lớn 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 bởi vì 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 lớn combine variables into a string.
$result= 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 menu of expressions for PHP to echo out và use a string with one blank space as one of those expressions: