PHP help with table

So I want to create a table with php and html that outputs a 10x10 table with numbers from 0 to 99 and differentiating prime numbers:

The problem is that every time it checks prime numbers from 0 to 99 it prints it in every '<tr>'. Ty in advance for the help!

<html>
 <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
   <?php  
        echo "<table>";
        for($i=0; $i < 10; $i++){
            echo "<tr>";
            for($x=0; $x < 10; $x++){
                for($i=0;$i<=99;$i++){
                    $counter = 0; 
                    for($j=1;$j<=$i;$j++){
                        if($i % $j==0){
                            $counter++;
                        }
                    }
                    if($counter==2){
                        echo "<td style="background-color: yellow;">".$i."</td>";
                    }else{
                        echo "<td style="background-color: blue>".$i."</td>";
                    }
                }
            echo "</tr>";
            }
        }
        echo "</table>";
    ?>  
</body>
</html>

It outputs a check of primer numbers from 0 to 99 every tr and i want it to be a single check from 0 to 99 using 10 tr

There are a few things wrong here.

  • First one: you’re using $i in two different for loops. This will break your outer loop as it won’t expect $i to be altered elsewhere.
  • Your echo statements are inside the prime checking loop, which isn’t where it should be.
  • Your quoting of the second echo <td> statement is incorrect.
  • Lots of single letter variables are making it tricky for you to keep track what’s going on.

I’m guessing this is homework / learning purposes, so I’ve relaid out the working code with comments below:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
</head>
<body>
<?php
echo "<table>";
// Our first row has no tens, our last row has nine
for ($tens=0; $tens<=9; $tens++) {
    echo "<tr>";
    // Our first column is [tens] plus one, our last column is [tens] plus ten
    for ($ones=1; $ones<=10; $ones++) {
        // Number we're working on
        $num = $tens * 10 + $ones;

        // Find the number of divisors
        $num_divisors = 0;
        for ($possible_divisor=1; $possible_divisor<=99; $possible_divisor++) {
            if ($num % $possible_divisor == 0) {
                $num_divisors++;
            }
        }

        if ($num_divisors == 2) {
            echo '<td style="background-color: yellow;">' . $num . '</td>';
        } else {
            echo '<td style="background-color: blue;">' . $num . '</td>';
        }
    }
    echo "</tr>";
}
echo "</table>";
?>
</body>
</html>
Sponsor our Newsletter | Privacy Policy | Terms of Service