Search code examples
phpfor-loopalphabetletter

PHP Vertical Alphabet Using FOR Cycle


I'm trying to do a script in PHP which will generate a table with vertical alphabet in it. It will simply echo letters from A to Z and when it comes to Z, it will reset and begin from A again. I have a problem with this because I only can repeat this twice, then all cells have some unwanted signs in them. I'm echo-ing the letter using their ASCII html codes, where the A sign is &#65 and the Z sign is &#90.

Here is the code I have until now, thanks for help.

<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <title>Vertical alphabet</title>
</head>
<body>
    <form method="post">
        <input type="number" placeholder="COLUMNS" name="cols" />
        <input type="number" placeholder="ROWS" name="rows" />
        <input type="submit" value="Create table" /><br><br>
    </form>

        <?php
            if(isset($_POST['rows']) && isset($_POST['cols'])) {
                $col = $_POST['cols'];
                $row = $_POST['rows'];

                echo ("<table rules='all'>");

                for($i = 1; $i<$row+1; $i++) {
                    echo ("<tr>");
                    for($c = 0; $c<$col; $c++) {
                        $letter_id = 65;
                        $number = ($i + ($c*$row)-1);
                        $letter = $number + $letter_id;
                        if($letter > 90) {
                            $number = $number - 26;
                            $letter = $letter - 26;
                            echo ("<td>". "&#" . $letter. "</td>");
                        } else {
                            echo ("<td>". "&#" . $letter. "</td>");
                        }
                    }
                    echo ("</tr>");
                }
                echo ("</table>");
            }
        ?>
</body>
</html>

Solution

  • Not sure what you're trying to with the $number variable, but that's the issue here

    $number = 0;
    
    echo ("<table rules='all'>");
    
    for($i = 1; $i<=$row; $i++) {
         echo ("<tr>");
         for($c = 0; $c<$col; $c++) {
              $letter_id = 65;
              $number = $i + ($c*$row);
              $letter = $number + $letter_id;
              while($letter > 90) {
                    $letter = $letter - 26;
              }
              echo ("<td>". "&#" . $letter. "</td>");
         }
         echo ("</tr>");
    }
    
    echo ("</table>");
    

    UPDATED:

    Now vertical, try this...