0

I am stuck here. I have this loop with if else condition, and I need else output in one iteration to change based on the output of the previous iteration. Here is the example:

$mr1 = 2;
$mc1 = 4;
$mr2 = 2;
$mc2 = 3;
$r = 5; $c = 5;
echo "<table>";
for ($i=1; $i <= $r; $i++) { 
    echo "<tr>";
    for ($n=1; $n <= $c; $n++) { 
        if ((($i == $mr1) AND ($n == $mc1)) || (($i == $mr2) AND ($n == $mc2))){
            echo "<td> * </td>";
        } else 
            echo "<td> 1 </td>";
    }
    echo "</tr><br>";
}
echo "</table><br><hr/><br>";

So in this loop if the condition is met output will be a * otherwise it will be number 1. What I don't know how to achieve is to make the code to output 2 if in previous iteration output was *. I hope you understand what I want to say? Thanx

Barmar
  • 741,623
  • 53
  • 500
  • 612
alenphp
  • 5
  • 2
  • 6
  • Can you add a variable that saves the 'previous' output and use that? – Ryan Apr 17 '15 at 20:50
  • you could make that `1` a variable, and in the `if` where you echo `*` increase the variable to `2` – Sean Apr 17 '15 at 20:52

2 Answers2

2

Use another variable:

$last_star = false;
for ($n=1; $n <= $c; $n++) { 
    if ((($i == $mr1) AND ($n == $mc1)) || (($i == $mr2) AND ($n == $mc2))){
        echo "<td> * </td>";
        $last_star = true;
    } elseif ($last_star) {
        echo "<td> 2 </td>";
        $last_star = false;
    } else { 
        echo "<td> 1 </td>";
        $last_star = false;
    }
}

BTW, get out of the habit of writing if and else clauses without braces around them. It's likely to cause problems when you're adding code to them (as I did above), if you forget to add the braces that are needed when you have multiple statements.

Why is it considered a bad practice to omit curly braces?

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I just wanted to add to @Barmar's answer that this is a common pattern in many languages, and is easily solved with a variable outside of the scope of the loop:

var outsideVariable = false;  //variable here is public and would work sometimes.
function()
{
// Variable could also be here to be outside only the for loop
  for ($n = 0; n < x; n++)
  {
     if (condition a) 
     {
     //Do stuff
     outsideVariable = false;
     }
     elseif (condition a & outsideVariable)
     {
     //do other stuff
     outsideVariable = false;     
     }
     else
     {
     //do other stuff
     outsideVariable = true;     
     }
  }
}

I know it isn't specific to your problem, but pointing out the scope hopefully will help both you and others on what Barmar demonstrated.

Austin T French
  • 5,022
  • 1
  • 22
  • 40