Saman22
Saman22

Reputation: 21

Multiplication Table PHP

I wanted to create a multiplication table with a custom function and also get the number of rows and columns from the user, and I want if each row was an even number then its field would be red (background) and if it was odd number it would have a green background and i also write some codes but i'm not sure if it's true or not:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
    <form method="post">
        <input type="number" name="rows" placeholder="Rows">
        <input type="number" name="columns" placeholder="Columns">
        <button type="submit" name="button">
            Create 
        </button>
    </form>
    <table border="1px">
        <?php

        if (isset($_POST["button"])) {

            $userRows = $_POST["rows"];
            $userColumns = $_POST["columns"];

            function multiplicationTable($rows, $columns)
            {
                $zarb = $rows * $columns;
                return $zarb;
            }

            $x = 1;
            while ($x <= $userRows) {
                echo "<tr>";
                $y = 1;
                while ($y <= $userColumns) {
                    if ($x % 2 == 0) {
                        echo "<td style='background-color: red;'>" . multiplicationTable($x, $y) . "</td>";
                    } else {
                        echo "<td style='background-color: green;'>" . multiplicationTable($x, $y) . "</td>";
                    }
                    $y++;
                }
                $x++;
                echo "</tr>";
            }
        }
        ?>
    </table>
</body>

</html>

Upvotes: 0

Views: 973

Answers (1)

syuffyq
syuffyq

Reputation: 13

How about changing the while loops to this:

while ($x <= $userRows) {
    echo "<tr>";
    $y = 1;
    while ($y <= $userColumns) {
        
        $val = multiplicationTable($x, $y);
        
        if ($val % 2 == 0) {
            echo "<td style='background-color: red;'>" . $val . "</td>";
        } else {
            echo "<td style='background-color: green;'>" . $val . "</td>";
        }
        $y++;
    }
    $x++;
    echo "</tr>";
}

Upvotes: 1

Related Questions