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";
2
  • 1
    echo => $stars.= Commented Aug 10, 2017 at 21:27
  • Also FYI, echo $stars; has the same effect as echo "$stars";. The double quotes aren't necessary. Commented Aug 10, 2017 at 22:13

3 Answers 3

6

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;
Sign up to request clarification or add additional context in comments.

Comments

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;

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.