Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP string concatenation [duplicate]

Is it 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 can’t use the + sign in concatenation, so what is the alternative?

like image 707
Illep Avatar asked Jul 11 '12 20:07

Illep


4 Answers

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

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

echo $result;
like image 199
abhshkdz Avatar answered Nov 17 '22 21:11

abhshkdz


One step (IMHO) better

$result .= $personCount . ' people';
like image 10
Loren Wolsiffer Avatar answered Nov 17 '22 21:11

Loren Wolsiffer


This should be faster.

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

echo $result;
like image 7
TurKux Avatar answered Nov 17 '22 20:11

TurKux


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

echo $result;
like image 6
Farly Taboada Avatar answered Nov 17 '22 21:11

Farly Taboada