xtarsy
xtarsy

Reputation: 153

Problems creating an ascii box with for-loops and if statements

In this exercise I am trying to create a box with for-loops and if statements. I am stuck and not sure which part of my code is wrong. Somehow the $aboxwidth values 1 and 4 get repeated twice.

When substituting spaces for 0 the output looks like this:

   output: 
        +0-0-0+0
        |000|0
        |000|0
        +0-0-0+0

    code:
<?php

//box builder
$iboxheight=4;
$aboxwidth=4;
//   +-----------+
//   |           |
//   |           |
//   |           |
//   +-----------+
//   +--+
//   |  |
//   |  |
//   +--+

//building boxheight
for ($i=1; $i <= $iboxheight; $i++) {
    //$boxwidth
    for ($a=1; $a <= $aboxwidth; $a++) {
        //build + in corners
    if (($i === 1 && $a === 1) || //corner top left
          ($i === 1 && $a === $aboxwidth)  ||  // corner top right
          ($i === $iboxheight && $a === 1)  ||  // corner bottom left
          ($i === $iboxheight && $a === $aboxwidth)) { // corner bottom right
        echo "+";
    }
        //build top and bottom
        if ($i === 1 || $i === $iboxheight) {
            if ($a !== 1 && $a !== $aboxwidth) {
                echo "-";
            }
        }
        //build walls
        if ($a === 1 || $a === $aboxwidth) {
            if ($i !== 1 && $i !== $iboxheight) {
                echo "|";
            }
        }
        if ($i !== 1 || $i !== $iboxheight) {
            if ($a !== 1 || $a !== $aboxwidth) {
                echo "0";
                //    echo "&nbsp;";
            }
        }
    }
    echo "<br>";
}

I am grateful for any tips and suggestions. Thanks

Upvotes: 0

Views: 39

Answers (1)

DinoCoderSaurus
DinoCoderSaurus

Reputation: 6520

The program will echo "0"; for every $i and $a. Why is that?

This ($i !== 1 || $i !== $iboxheight) is always true. And this $a !== 1 || $a !== $aboxwidth is always true. When $i is 1, it is not equal $iboxheight, therefore true. When $a is 1, it is not equal $aboxwidth, therefore true. And so on. The program echo's 0 for every iteration.
(You might try echo "($i,$a)"; in place of echo "0"; to see it in action).

If the || are changed to && it would accomplish the desired result, ie only echo {whatever} when the (row,column) is not on the "border".

Upvotes: 1

Related Questions