总结
豆包 AI 助手文章总结
首页 > Java > java教程 > 正文

在PHP中拼接两个字符串

PHPz
发布: 2023-09-02 22:25:06
转载
897人浏览过

在php中拼接两个字符串

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.

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
登录后复制

以上就是在PHP中拼接两个字符串的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号