1

I have this PHP code that works:

for ($i=0; $i < 5; $i++) {
    do stuff to $class
    echo "<i class=\"glyphicon glyphicon-star $class\"></i>";
}

Instead of using echo in the loop, how would I append each iteration to a variable (say $stars) and then be able to display the result with

echo "$stars";
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
jasenmichael
  • 388
  • 5
  • 17

3 Answers3

5

Create a variable to hold your HTML. Concatenate the HTML to this variable instead of echoing it.

After the loop you can echo that variable.

$stars = '';
for ($i=0; $i < 5; $i++) {
    // do stuff to $class
    $stars .= "<i class=\"glyphicon glyphicon-star $class\"></i>";
}
echo $stars;
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
3

You can use Concatenation assignment .= like this

$var='';
for ($i=0; $i < 5; $i++) {
    do stuff to $class
    $var.="<i class=\"glyphicon glyphicon-star $class\"></i>";
}
echo $var;
Spoody
  • 2,852
  • 1
  • 26
  • 36
1

Alternatively, you can do this without modifying your existing code using output buffering.

// start a new output buffer
ob_start();

for ($i=0; $i < 5; $i++) {
    //do stuff to $class

    // results of these echo statements go to the buffer instead of immediately displaying
    echo "<i class=\"glyphicon glyphicon-star $class\"></i>";
}

// get the buffer contents
$stars = ob_get_clean();

For a simple thing like this I would still use concatenation with .= as shown in the other answers, but just FYI.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80