JaedynO
JaedynO

Reputation: 23

For loop in PHP with a unique output for only one loop

I have a project where I have inputs that decide the range of numbers echoed but I also need to have a single number echo more text. At the moment I have an if statement which works but echoes the number a second time.

for ($x = $var1; $x <= $var2; $x += $varInc) {
    echo "<p>$x</p>";
    if ($x == $varGhost){
        echo "<p class='fas fa-ghost'></p>";
    }
}

It's supposed to look similar to this:

enter image description here

Upvotes: 1

Views: 54

Answers (2)

Alessandro Tedesco
Alessandro Tedesco

Reputation: 144

It isn't working as expected because the second line echoes the number $x in any case, regardless the following if statement:

for ($x = $var1; $x <= $var2; $x += $varInc) {
    echo "<p>$x</p>"; // this line echoes the number $x in any case
    if ($x == $varGhost) {
        echo "<p class='fas fa-ghost'></p>";
    }
}

You should check the value of $x before printing it like this:

for ($x = $var1; $x <= $var2; $x += $varInc) {
    if ($x == $varGhost) {
        echo "<p class='fas fa-ghost'></p>";
    }
    else {
        echo "<p>$x</p>"; // this line echoes the number $x ONLY if it isn't a ghost
    }
}

Anyway, a shorter way to write it:

for ($x = $var1; $x <= $var2; $x += $varInc)
    echo ($x == $varGhost) ? "<p class='fas fa-ghost'></p>" : "<p>$x</p>"

Hope it helps :)

Upvotes: 0

Szymek
Szymek

Reputation: 163

You should change your code to:

for ($x = $var1; $x <= $var2; $x += $varInc) {
 if ($x == $varGhost){
    echo "<p>$x - GHOST!</p>";
 } else {
    echo "<p>$x</p>";
 }
}

I hope it works :)

Upvotes: 2

Related Questions