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 (".="):
立即学习“PHP免费学习笔记(深入)”;
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.
<?php $a = 'Good'; $b = 'Morning'; $c = $a.$b; echo " $c "; ?>
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
以上就是在PHP中拼接两个字符串的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号