问题
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 ?
回答1:
Just use . for concatenating.
And you missed out the $personCount increment!
while ($personCount < 10) {
$result .= $personCount . ' people';
$personCount++;
}
echo $result;
回答2:
One step (IMHO) better
$result .= $personCount . ' people';
回答3:
while ($personCount < 10) {
$result .= ($personCount++)." people ";
}
echo $result;
回答4:
This should be faster.
while ($personCount < 10) {
$result .= "{$personCount} people ";
$personCount++;
}
echo $result;
回答5:
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;
回答6:
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;
回答7:
$personCount=1;
while ($personCount < 10) {
$result=0;
$result.= $personCount . "person ";
$personCount++;
echo $result;
}
来源:https://stackoverflow.com/questions/11441369/php-string-concatenation