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.
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.
string
with no data in it. This is where the data we later append is placed.string
ten times. It is modified after each append in the for
-loop.string
. Here we place a string
containing the word "Result
" in front.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.
The implode and join functions "merge" the strings from an array together. They are the same function with different names.
string
argument. This results in a string
with two comma delimiters in it.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.