PHP string concatenation

2019-01-02 21:14发布

I need to know if its possible to concatenate strings, as follows ? and if not, what is the alternative of doing so ?

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

echo $result;

it should appear like 1 person 2 person 3 person etc..

You cann't use the + sign in concatenation so what is the alternative ?

7条回答
看风景的人
2楼-- · 2019-01-02 21:25
while ($personCount < 10) {
    $result .= ($personCount++)." people ";
}

echo $result;
查看更多
公子世无双
3楼-- · 2019-01-02 21:34

I think this code should work fine

while ($personCount < 10) {
$result = $personCount . "people ';
$personCount++;
}
// do not understand why do you need the (+) with the result.
echo $result;
查看更多
ら面具成の殇う
4楼-- · 2019-01-02 21:35

That is the proper answer I think because PHP is forced to re-concatenate with every '.' operator. It is better to use double quotes to concatenate.

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

echo $result;
查看更多
无与为乐者.
5楼-- · 2019-01-02 21:39
$personCount=1;<br/>
while ($personCount < 10) {<br/>
    $result=0;<br/>
    $result.= $personCount . "person ";<br/>
    $personCount++;<br/>
    echo $result;<br/>
    }
查看更多
梦该遗忘
6楼-- · 2019-01-02 21:44

This should be faster.

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

echo $result;
查看更多
路过你的时光
7楼-- · 2019-01-02 21:47

Just use . for concatenating. And you missed out the $personCount increment!

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

echo $result;
查看更多
登录 后发表回答