62

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Illep
  • 16,375
  • 46
  • 171
  • 302

6 Answers6

99

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

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

echo $result;
abhshkdz
  • 6,335
  • 1
  • 21
  • 31
10

One step (IMHO) better

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

This should be faster.

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

echo $result;
TurKux
  • 105
  • 1
  • 3
  • 4
    Care to cite any evidence that `"{$personCount} people"` is faster than `$personCount . ' people'`? Otherwise it just seems like wild speculation... – Jake Dec 09 '17 at 23:33
  • PHP is forced to re-concatenate with every '.' operator. It is better to use double quotes to concatenate. – Abdul Alim Shakir Apr 05 '18 at 03:43
  • 1
    @Abdul Alim Shakir: But there is only one concatenation, so it shouldn't make any difference(?). – Peter Mortensen May 16 '21 at 09:48
  • Using `.` instead `.=` (the first instance) *does* affect performance (probably due to the [Schlemiel the Painter's algorithm](https://en.wikipedia.org/wiki/Joel_Spolsky#Schlemiel_the_Painter's_algorithm) - this can happen in *any* language or system), but it is ***already*** using `.=`. – Peter Mortensen May 16 '21 at 10:20
  • cont': From *[Assignment Operators](https://www.php.net/manual/en/language.operators.assignment.php)*: *"Using `$text .= "additional text";` instead of `$text = $text . "additional text";` can seriously enhance performance due to memory allocation efficiency. I reduced execution time from 5 seconds to 0.5 seconds (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end."* – Peter Mortensen May 16 '21 at 10:26
6
while ($personCount < 10) {
    $result .= ($personCount++)." people ";
}

echo $result;
0

I think this code should work fine:

while ($personCount < 10) {
    $result = $personCount . "people ';
    $personCount++;
}
# I do not understand why you need the (+) with the result.
echo $result;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
salim
  • 11
0
$personCount = 1;
while ($personCount < 10) {
    $result = 0;
    $result .= $personCount . "person ";
    $personCount++;
    echo $result;
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 6
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – Nic3500 Aug 09 '18 at 10:33