2012-07-11 61 views
40

我需要知道它是否可以连接字符串,如下所示?如果不是,那么这样做有什么选择?PHP字符串连接

while ($personCount < 10) { 
$result+= $personCount . "person "; 
} 

echo $result; 

它应该出现像1 person 2 person 3人等。

您水湿使用+登录级联那么什么是另类?

+8

您实际上在示例代码中使用了“替代”。 – lanzz 2012-07-11 20:59:07

+0

[参考 - 这个符号在PHP中意味着什么?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – mario 2012-07-11 22:57:14

+2

我发现它很难相信没有人指出你使用“人”而不是“人”。 – 2017-07-04 08:43:44

回答

71

只需使用.进行连接。 而你错过了$personCount增量!

while ($personCount < 10) { 
    $result .= $personCount . ' people'; 
    $personCount++; 
} 

echo $result; 
7

的一个步骤(恕我直言)更好

$result .= $personCount . ' people'; 
0

我觉得这个代码应该可以正常工作

while ($personCount < 10) { 
$result = $personCount . "people '; 
$personCount++; 
} 
// do not understand why do you need the (+) with the result. 
echo $result; 
+3

看到你有''people''而不是'people'' – PhoneixS 2014-01-21 11:55:32

+0

你可能会因为@PhoneixS指出的错误而导致大量错误:不匹配的引号 – 2017-07-04 08:45:49

3
while ($personCount < 10) { 
    $result .= ($personCount++)." people "; 
} 

echo $result; 
3

这应该会更快。

while ($personCount < 10) { 
    $result .= "{$personCount} people "; 
    $personCount++; 
} 

echo $result; 
+0

注意引用任何证据证明'“{$ personCount} people“'比'$ personCount''people''更快吗?否则它就像疯狂的猜测一样...... – Jake 2017-12-09 23:33:37