Home
Map
String Concat ExamplesUse the string concat operator to append one string to another.
PHP
This page was last reviewed on Nov 7, 2023.
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.
foreach
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 7, 2023 (grammar).
Home
Changes
© 2007-2024 Sam Allen.