首页 > 文章列表 > 在PHP中拼接两个字符串

在PHP中拼接两个字符串

php 拼接字符串 字符串连接
247 2023-09-02

PHP offers different kinds of operators having distinctive functionalities. Operators enable us to perform arithmetic activities, string concatenation, compare values and to perform boolean operations, more...In this article, we will learn string operators given by PHP. Let's first learn the types of string operators in php. There are two string operators provided by PHP. 

 1.Concatenation Operator ("."): 

     This operator combines two string values and returns it as a new string.

 2.Concatenating Assignment operator (".="): 

     This operation attaches the argument on the right side to the argument on the left side.

 Let's demonstrate the utility of the above operators by following examples.

Example:

<?php
$a = 'Good';
$b = 'Morning';
$c = $a.$b;
echo " $c ";
?>

Output :

Goodmorning

解释:

这里我们取了两个变量$a和$b作为字符串。然后我们使用连接运算符(.)将这些字符串连接成一个字符串。

例子:

<?php
   $a = 'Hello';
   $b = [" Good morning"," Folks"];
   for($i = count($b)-1; $i >= 0;$i--) {
$a .= $b[$i];
}
echo " $a";
?>

输出:

Hello Folks Good morning

解释:

在这个例子中,我们使用连接赋值运算符(".=")将字符串值与数组值连接起来。$a表示一个字符串,而$b表示一个数组,我们使用for循环将字符串$a与数组$b的值连接起来。

注意:

连接运算符('.')与"+"和" -"运算符具有相似的优先级,可能会产生意外的结果。

例子:

<?php
$val = 5;
echo "Result: " . $val + 5;
?>

输出:

5

解释:

上述代码将打印出“5”而不是“Result: 10”,因为首先创建了字符串“Result5”,然后将其与5相加,得到5。这是因为非空非数字字符串“Result5”将被转换为0,并与5相加得到5。要打印出“Result: 10”,请使用括号改变优先级:

<?php
$var = 5;
echo "Result: " . ($var + 5);
?>

输出:

Result:10