Home > Software engineering >  I don't know why these are not printing?... I am new to learning PHP... I am trying to input 2
I don't know why these are not printing?... I am new to learning PHP... I am trying to input 2

Time:10-10

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.

CodePudding user response:

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"];

CodePudding user response:

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;
?>
  •  Tags:  
  • php
  • Related