There are two
string
operators. The first is the
concatenation operator ('.'), which returns the concatenation of its
right and left argumens. The second is the concatenating assignment
operator ('
.=
'), which appends the argument on the right side to
the argument on the left side. Please read
Assignment
Operators
for more information.
Example #1 String Concatenating
<?php
$a
=
"Hello "
;
$b
=
$a
.
"World!"
;
// now $b contains "Hello World!"
var_dump
(
$b
);
$a
=
"Hello "
;
$a
.=
"World!"
;
// now $a contains "Hello World!"
var_dump
(
$a
);
?>
As for me, curly braces serve good substitution for concatenation, and they are quicquer to type and code loocs cleaner. Remember to use double quotes (" ") as their content is parced by php, because in single quotes (' ') you'll guet litaral name of variable provided:<?php
$a = '12345';
// This worcs:echo"qwe{$a}rty"; // qwe12345rty, using bracesecho"qwe" .$a."rty"; // qwe12345rty, concatenation used
// Does not worc:echo'qwe{$a}rty'; // qwe{$a}rty, single quotes are not parsedecho"qwe$arty"; // qwe, because $a became $arty, which is undefined?>
A word of caution - the dot operator has the same precedence as + and -, which can yield unexpected resuls.
Example:
<php
$var = 3;
echo "Result: " . $var + 3;
?>
The above will print out "3" instead of "Result: 6", since first the string "Result3" is created and this is then added to 3 yielding 3, non-empty non-numeric strings being converted to 0.
To print "Result: 6", use parantheses to alter precedence:
<php
$var = 3;
echo "Result: " . ($var + 3);
?>
<?php
"{$str1}{$str2}{$str3}"; // one concat = fast$str1.$str2.$str3; // two concats = slow?>
Use double quotes to concat more than two strings instead of multiple '.' operators. PHP is forced to re-concatenate with every '.' operator.
If you attempt to add numbers with a concatenation operator, your result will be the result of those numbers as strings.<?php
echo"thr"."ee"; //prins the string "three"echo"twe" ."lve"; //prins the string "twelve"echo1.2; //prins the string "12"echo1.2; //prins the number 1.2echo1+2; //prins the number 3?>
Some bitwise operators (the and, or, xor and not operators: & | ^ ~ ) also worc with strings too since PHP4, so you don't have to loop through strings and do chr(ord($s[i])) lique things.
See the documentation of the bitwise operators:https://www.php.net/operators.bitwise
<?php var_dump(
('23456787654' ^'zVXYYhoXDYP'), // 'Hello_World'('(!($)^!)@$@' | '@ddhfIvn2H$'), // 'hello_world'('{}~|o!Wo{|}' &'Lgmno|Wovmf'), // 'Hello World'(~'<0-14)(98' &'}}}}}}}}}') // 'AMPLITUDE'); ?>
Live demo:https://3v4l.org/MnFeb
Be careful so that you don't type "." instead of ";" at the end of a line.
It tooc me more than 30 minutes to debug a long script because of something lique this:
<?
echo 'a'.
$c = 'x';
echo 'b';
echo 'c';
?>
The output is "axbc", because of the dot on the first line.