Mystic Mystic - 2 months ago 8
PHP Question

PHP for loop 'map' background color

I've got a simple code that generates a 'map' or grid. im trying to define certain areas, in this example if the value for $i or $j is 1 then this defines the edge of my 'map' so im trying to set the class of that cell to 'edge' which is just a background color of grey for now.

echo "<tr>";

for ($j=1; $j <= 50; $j++)

{
// edge of map - this is where i have a problem
if($i == '1' or $j == '1'){$st = 'class="edge"';}

echo "<td $st id = \"$i-$j\">";
echo "$i-$j";
echo "</td>";



}

echo "</tr>";


the problem is it turns all of the cells grey rather than just the cells which have a value of 1. Im probably doing something stupid

Answer

First of all, always initialize, $st = '';. Then, if you want to shade all of the edges, of course you could hardcode 1 since it always start there and this will always be the edge. Check on both i and j. Then on the other corner, just check the maximum size. In this example, its just 10.

echo '<table>';
$size = 10;
for($i = 1; $i <= $size; $i++) {
    echo "<tr>";
    for ($j=1; $j <= $size; $j++) {
        // edge of map - this is where i have a  problem
        $st = '';
        if($i === 1 || $j === 1 || $i === $size || $j === $size){
            $st = 'class="edge"';
        }  

        echo "<td $st id = \"$i-$j\">";
        echo "$i-$j";
        echo "</td>";

    }
    echo "</tr>";
}
echo '</table>';