skip to Main Content

This is my HTML file. I have two inputs where user will enter 2 numbers and submit for the "calculation".

<html>
    <head>
        <title>Larger of two numbers</title>
    </head>
    <body>
    <form action = "largeroftwonum.php" method = "post">
      Enter your first number: <input type = "text" width = "5" maxlength="4" name = "first">
      <br>
      Enter your second number: <input type = "text" width = "4" maxlength="4" name = "second">
        <br>
        <input type = "submit" value = "Click to Submit">
        <input type = "reset" value = "Click to Reset">
    </form>
    
    </body>
    </html> 

And this is my PHP code. This is where it simply compares the two numbers and prints/returns the bigger number of the two.

        <html>
    <head>
        <title> Larger of two numbers PHP </title>
    </head>
    <body>
    <?php
    $one = $_POST["$first"]; $two = $_POST["$second"];
    largerTwo($one, $two);
    function largerTwo ($one, $two) {
        if ($one > $two) {
            print "$one";
            return $one;
    } else {
            print "$two";
            return $two;
        }
    }
    ?>
    
    </body>
    </html>

Sorry in advance if it’s such a simple task. I really need some guidance.

2

Answers


  1. The dollar sign in the double quote ($_POST["$first"];) means the value of $first that in your example is undefined.

    Replace $one = $_POST["$first"]; $two = $_POST["$second"]; by $one = $_POST["first"]; $two = $_POST["second"];

    Login or Signup to reply.
  2. Get the integer value of first and second.
    Make an array with the two values: [$first,$second]
    Return the max()value of the array.

    $first = intval($_POST['first']);
    $second= intval($_POST['second']);
    $max= max([$first,$second]);
    

    Best practice for PHP generated HTML there should be <?php only on line one and ?> only on the last line.

    <?php
    
    $first = intval($_POST['first']);
    $second= intval($_POST['second']);
    $max= max([$first,$second]);
    
    echo <<<EOT
    <html><head><title> Larger of two numbers PHP </title></head><body>
    Values = $first and $second<br>
    The larger value is $max
    </body></html>
    EOT;
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search