1

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

1
  • It echoes the number a second time? It doesn't look like it would do that. Commented Nov 15, 2019 at 0:23

2 Answers 2

2

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 :)

Sign up to request clarification or add additional context in comments.

Comments

0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.