Home >Backend Development >PHP Tutorial >通常拼字符串用哪种方式呀

通常拼字符串用哪种方式呀

WBOY
WBOYOriginal
2016-06-13 11:12:49970browse

一般拼字符串用哪种方式呀
$a = "aa";
$b = "bb";
$str = "{a:".$a.",b:".$b."}"; 

$str1 = "{a:$a,b:$b}";

$str2 = sprintf("{a:%s,b:%s}",$a,$b);
echo $str;
echo $str1;
echo $str2;

3中了  
一般哪种好些,或者说是有不同的场景.... 各有各的号

还有其他的拼字符串的方式吗???


------解决方案--------------------
$a = "aa";<br />$b = "bb";<br />$array = array();<br />$array['a'] = $a;<br />$array['b'] = $b;<br />echo json_encode($array);


demo:
http://sandbox.onlinephpfunctions.com/code/d3f616489979148ab4896c38b8a17b034259daab
------解决方案--------------------
有精度需求时,我一般用sprintf。
------解决方案--------------------
<br />$a = 'aa';<br />$b = 'bb';<br />$array = array (<br />		'a' => $a,<br />		'b' => $b <br />);<br />$str2 = json_encode ( $array );<br />echo $str2;<br />


建议:给字符串赋值尽量少用双引号,用单引号。
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn