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";
Another form available is this:
Concatenate them with the
.
operator:Or use string interpolation:
is more generic.
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 argumentsIf you want to append a string to another string you would use the
.=
operator: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.
Note: this will also work without the braces in your case:
Use
sprintf()
orprintf()
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.printf()
does the same thing but will immediately display the output.Heredoc
Heredocs can also be used to combine variables into a string.
Use a
,
withecho()
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:
You can do this using PHP:
This will combine two strings and the putput will be: "the color is red!".
I believe the most performant way is:
If you want to implement localisation, you may do something like this:
It's a bit slower, but it does not assume grammar rules.