Concat. It is often necessary to append one string to another in PHP. And sometimes we must append a string to the start of another (prepend).
With the concat operator, which is the period char, we can combine 2 strings. And with curly braces we can use formatting to combine a string with literals.
Example. This example program demonstrates how to combine strings together with the concat operator. It also uses curly braces in a format string to combine strings.
Step 1 We create a new string with no data in it. This is where the data we later append is placed.
Step 2 We append a single lowercase letter "x" to the string ten times. It is modified after each append in the for-loop.
Step 3 It is also possible to prepend a string. Here we place a string containing the word "Result" in front.
Step 4 We use curly braces to surround the result string inside of a pattern. This has a leading word, and a newline at the end.
// Step 1: create new empty string.
$result = "";
// Step 2: append the letter "x" ten times.
for ($i = 0; $i < 10; $i++) {
$result .= "x";
}
echo $result . "\n";
// Step 3: append the string to a leading string.
$result = "Result: " . $result;
echo $result . "\n";
// Step 4: use curly braces to place the string inside another.
$result = "CAT: {$result}.\n";
echo $result;xxxxxxxxxx
Result: xxxxxxxxxx
CAT: Result: xxxxxxxxxx.
Implode, join. The implode and join functions "merge" the strings from an array together. They are the same function with different names.
Version 1 We call implode with a comma string argument. This results in a string with two comma delimiters in it.
Version 2 We can use implode with just an array argument. There are no delimiters used—the strings are mashed together.
Version 3 We test out the join() function, which is just an alias for implode() so no different in results is found.
$colors = ["blue", "orange", "green"];
// Version 1: combine with comma chars in between.
$result = implode(",", $colors);
var_dump($result);
// Version 2: no delimiter implode.
$result = implode($colors);
var_dump($result);
// Version 3: join is the same as implode.
$result = join(",", $colors);
var_dump($result);string(17) "blue,orange,green"
string(15) "blueorangegreen"
string(17) "blue,orange,green"
Changing two strings into one is often done in PHP, and we have clear syntax for this operation. It is possible do this concatenation operation in a variety of ways.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Nov 7, 2023 (grammar).